I have data in MongoDB in the form of :
{
"_id" : 154,
"record_id" : "001280000033x54AAA",
"jsonData" : "",
"user_id" : 1,
"userName" : "abc@xyz.com",
"backup_no" : 1
}
{
"_id" : 155,
"record_id" : "001280000033x54AAA",
"jsonData" : "",
"user_id" : 1,
"userName" : "abc@xyz.com",
"backup_no" : 2
}
...
I want to retrieve data based on 'user_id','userName', but if a record with same record_id exists in lower 'backup_no' then i need to choose record with highest backup_no.
I have tried to aggregate record_id's and then query but i am unable to find a solution.
Thanks
Using mongo aggregation
you can get your results check below query :
db.collectionName.aggregate({
"$sort": {
"backup_no": -1 //first sort by backup_no
}
}, {
"$group": {
"_id": "$record_id", // group by record_id so here only get distinct record_id
"userId": {
"$first": "$user_id"
},
"userName": {
"$first": "$userName"
},
"backup_no": {
"$first": "$backup_no"
}
}
}, {
"$project": {
"_id": 0,
"record_id": "$_id",
"user_id": "$user_id",
"userName": "$userName",
"backup_no": "$backup_no"
}
})
db.collection.aggregate([{
$group: {
_id: "$record_id",
user_id: {
$last: "$user_id"
},
userName: {
$last: "$userName"
},
backup_no: {
$max: "$backup_no"
}
}
}])
or
You could simply sort descending by backup_no and then ignore all but the first record for each distinct record_id?
MongoDB $orderby
db.users.find( { } ).sort( { backup_no: -1 } );