aggregation framework - MongoDB - Query - Top Document per Group -
this question has answer here:
i have following sql (mysql) query, , convert mongodb. getting top 1 document in every group:
select a.* ads inner join (select id ads userid = 1 group ad_code having max(ad_timestamp)) b on b.id = a.id
from have read far there several ways aggregate data in mongodb (more info @ mongodb aggregation comparison: group(), $group , mapreduce):
- group (does not work on sharded collections)
- mapreduce
- $group
i trying solve mongodb aggregation framework. far have this:
db.ads.aggregate([ { $match: { userid: objectid("5976e215769d8a4a4d75c514") } }, { $group: { _id: "$ad_code", latesttimestamp: { $max: "$ad_timestamp" }, } } ])
but not return _ids of matching documents, ad code , max timestamp, cannot use data whole documents.
this question looks relevant, doesn't seem solve same issue i'm having: query 1 document per association mongodb
thanks
edit duplicate flag: question different others, , different question linked, in solution uses $first
operand find 1-match, , docids
field retrieve un-aggregated original documents. different how other questions have approached solutions, partly result of evolution of mongodb on time.
it doesn't returns _id
because didn't asked it. try query instead :
db.ads.aggregate([ { $match: { userid: objectid("5976e215769d8a4a4d75c514") } }, { $sort: {"ad_timestamp": -1}}, { $group: { _id: "$ad_code", latesttimestamp: { $first: "$ad_timestamp" }, docids: {$first: "$_id"} } } ])
here first sort ad_timestamp
, first of each group $first
, , same _id
Comments
Post a Comment