mongodb - Mongo:. How to get unique rows -
i have following object , record has keyword , deviceid.
there multiple object same deviceid. last entry each device id
{ search:{ keyword:"_" }, datecreated:"", device:[{ deviceid:"_" }], }
example
{ search:{ keyword:"fl" }, datecreated:"01/01/2017", device:[{ deviceid:"1" }], } { search:{ keyword:"atl" }, datecreated:"01/02/2017", device:[{ deviceid:"1" }], } { search:{ keyword:"ga" }, datecreated:"01/03/2017", device:[{ deviceid:"2" }], }
the query should return
{ search:{ keyword:"atl" }, datecreated:"01/02/2017", device:[{ deviceid:"1" }], } { search:{ keyword:"ga" }, datecreated:"01/03/2017", device:[{ deviceid:"2" }], }
you can not achieve using "datecreated",first need convert "datecreated" column in date format(in context mongo iso date). after that, can run following achieving last entry mentioned in question
db.abc.aggregate([ { "$unwind": "$device" }, {$group: { _id: "$device", search: { "$max": "$search" }, datecreated: { "$max": "$datecreated" } } } ])
and if looking same json format can project query,
db.abc.aggregate([ { "$unwind": "$device" }, { $group: { _id: "$device", device: { "$push": "$device" }, search: { "$max": "$search" }, datecreated: { "$max": "$datecreated" } } }, { $project: { search: 1, datecreated: 1, device: 1, _id: 0 } } ])
Comments
Post a Comment