Reputation: 95
I have a domain "Notification"
{
_id: 1
is_action: false,
user:[{
user_id: 5,
status: "R"
},
{
user_id: 8,
status: "U"
}],
priority:1
},
{
_id: 2
is_action: true,
user:[{
user_id: 5,
status: "U"
},
{
user_id: 8,
status: "U"
}],
priority:1
}
My query to find notification where user_id = 5 ------
db.notifications.aggregate([
{$unwind:"$user"},
{$match:{
"user.user_id":5,
is_action: false
}},
{$sort:{priority:1}}
])
But I need to sort the above query according to the following condition
if(status == "U"){
Sort by "priority"
}else{
Sort by "_id"
}
Upvotes: 2
Views: 286
Reputation: 1952
Use $cond to create a new field, e.g.
{
$project:
{
otherfield: 1,
sortField: {
$cond: { if: { $eq: [ "$status","U" ] },
then: "$priority",
else: "$_id" }
}
}
}
And then sort this field.
P.S. $cond is a new operator in MongoDB version 2.6 and above
Upvotes: 2