some problems with mongoDB - how to get last row value exist on group condition -
i have problem mongo.
i need last name of row if exist. mongo document { _id: object... campaign: 1 total: 1 ...: . .. campaignname: "name of campaign" how see "campaignname" missing on tree position of collection
}, { _id: object... campaign: 2 total:3 ...: . .. campaignname: "name of campaign 2"
}, { _id: object... campaign: 1 total: 1 ...: . .. campaignname: "z name of campaign"
}, { _id: object... campaign: 1 total: 6 ...: . .. }
if this:
db.dataweek.aggregate([{ $project: { "campaignname": 1 } }, { $group: { _id: { "$_id", "$campaign" }, campaignname: { $last: "$campaignname" }, total: { $sum: "$total" } } }]) i result ok if last rows have field campaignname, if not null name field.
my question how last campaignname value exists ( group campaign ) .
and result should like:
campaign: 1 total: 8 .. campaignname: "z name of campaign"
campaign: 2 total: 3 .. campaignname: "name of campaign 2"
....
you can see name of campaign 1 has changed
ps. $first not valid, need last campaignname exists diferrent ''
in nutshell need $sort documents first before grouping expected result last. consider following sample:
{ "a" : 1, "title" : "here" } { "a" : 1 } { "a" : 1, "title" : "there" } { "a" : 2 } { "a" : 2, "title" : "here" } { "a" : 2, "title" : "there" } { "a" : 1 } { "a" : 2 } so find last valid "title" when grouping "a" , obtaining count, first sort grouping key , "title". entries not contain title listed first:
db.collection.aggregate([ { "$sort": { "a": 1, "title": 1 } }, { "$group": { "_id": "$a", "title": { "$last": "$title" }, "total": { "$sum": 1 } }} ]) of course results sorted on field "t" come after "h" in example. if had result "sort" on such "date" important include in sort order first:
{ "$sort": { "a": 1, "date": 1, "title": 1 } } but there no other way ensure $last cannot
"last if value exists"
the $exists clause query portion remove entries not present, change "count" on results. there $ifnull operator evaluates whether field present , alternately returns value, no use without "sort".
also note single field not looking multiple fields or "last" entry other sorted condition, $max operator same thing without having apply sort.
Comments
Post a Comment