mongodb - Get latest document in collection for each user -


i need latest document in collection each user in collection. example, lets assume have data this:

[     { user: "bob", time: isodate("sat, 24 mar 2012 05:52:21 +0000"), value: "a" },     { user: "bob", time: isodate("sun, 25 mar 2012 05:52:21 +0000"), value: "b" },     { user: "joe", time: isodate("sat, 24 mar 2012 05:52:21 +0000"), value: "c" },     { user: "bob", time: isodate("mon, 26 mar 2012 05:52:21 +0000"), value: "d" },     { user: "joe", time: isodate("sun, 25 mar 2012 05:52:21 +0000"), value: "e" } ] 

after querying, want these entries:

[     { user: "bob", time: isodate("mon, 26 mar 2012 05:52:21 +0000"), value: "d" },     { user: "joe", time: isodate("sun, 25 mar 2012 05:52:21 +0000"), value: "e" } ] 

i saw question here: mongodb map-reduce find values last record per user, doesn't quite seem right answer i'm looking for. how query data?

you can use $last operator .aggregate() method this:

db.collection.aggregate([     { "$sort": { "user": 1, "time": 1 } },     { "$group": {         "_id": "$user",         "time": { "$last": "$time" },         "value": { "$last": "$value" }     }} ]) 

so taking "last" items grouping boundary return values. use of $last makes sense after sort in cases, increasing inserts stage can excluded.

probably worth noting use _id value in place of time-stamp $sort on it's value increases well.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -