When I run a query with your exact data, the Sheldon document is returned because when you compare the string “2 hours ago” with the string “5 hours ago”, the character “2” is less than the character “5” "so the document will be correctly returned. String 10 hours ago also sorted as less than 5 hours ago.
However, if you tune the data to actual numbers as shown below, the Sheldon document is not returned.
So your query looks good to me, you just need to replace the timestamps with either Dates, numbers, or even strings that are structured so that they will be sorted in the correct order.
Modified data:
{ name: "Sheldon", events: [ { event: "View", timestamp: -10 }, { event: "Some other event", timestamp: -8 }, { event: "View", timestamp: -2 } ] }, { name: "Leonard", events: [ { event: "View", timestamp: -10 } ] }, { name: "Howard", events: [ { event: "View", timestamp: -2 } ] }, { name: "Raj", events: [ { event: "Some other event", timestamp: -6 } ] }
Modified request:
{ $and: [ { 'events': { $not: { $elemMatch: { event: "View", timestamp: { $gte: -5 } } } } } ] }
Result:
{ "name" : "Leonard", "events" : [ { "event" : "View", "timestamp" : -10 } ] } { "name" : "Raj", "events" : [ { "event" : "Some other event", "timestamp" : -6 } ] }
sheilak
source share