haejeong87
haejeong87

Reputation: 957

Mongodb Query on a field of a last document in a nested Array

I come from SQL world, and still learning to query MongoDB, and I faced this problem...

Setup:

I have a Student collection which has an array of Meetings

student: {
  meetings: [
    {time: x},
    {time: y},
    {time: z}
  ]
}

meetings array has a dynamic size, and its elements are sorted by time in asc, so the first meeting in the array would have the earliest time.

I am able to query to get all students whose first meeting begins after certain time by:

db.students.find( { "meetings.0.time": {$gt: ISODate()} } )

Question:

Now I also need to query to get all students whose LAST meeting begins before certain time. However, the following didn't work:

db.students.find( { "meetings.-1.time": {$lt: ISODate()} } )

How would you guys solve this problem?

Upvotes: 1

Views: 2546

Answers (1)

sambomartin
sambomartin

Reputation: 6813

Does this work for you?

db.student.aggregate(
  { $unwind : "$meetings" },
  { $group : { _id: "$_id", lastMeeting : { $max : "$meetings.time" }}},
  { $match: { lastMeeting : { $lt : IsoDate(...) } } 
);

Upvotes: 1

Related Questions