1

I have a people collection with a timeline array containing a year when something happened to this person. For example the year they were born, like this:

db.people.insert({
  "timeline": [
    { "born_year": 1999 },
    { "other_event": 2005 }
  ]
});

I can query this collection for someone born 1999:

db.people.find({
  "timeline": { $in: [ { "born_year": 1999 } ] }
});

However, when using $lt to query for people born before 2000 I don't get any results at all:

db.people.find({
  "timeline": { $in: [ { "born_year": { $lt: 2000 } } ] }
});

Can anyone explain to me what I'm doing wrong here?

1 Answer 1

2

You should be using dot notation to target specific element properties rather than matching entire elements as objects:

db.people.find({
  "timeline.born_year": { $lt: 2000 }
});

This will find all docs that have a timeline array element with a property of born_year with a value < 2000.

For the exact comparison:

db.people.find({
  "timeline.born_year": 1999
});
Sign up to request clarification or add additional context in comments.

2 Comments

This would require a minor structure change to the objects, but it would be a wise change.
Btw, Brandon what kind of structure change would be wise to use and why? I'm just starting to learn MongoDB so all tips are welcome :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.