Reputation: 13
I have a set of data. When I select the filter conditions, I want to query all the data and put the values that conform to the screening conditions to display in front of the query results.
for example
[
{color: 'blue', name: 'four'},
{color: 'green', name: 'five'},
{color: 'red', name: 'one'},
{color: 'red', name: 'two'},
{color: 'red', name: 'three'}
]
when i choose color:red
, and limit 4, I want to get the data
[
{color: 'red', name: 'one'},
{color: 'red', name: 'two'},
{color: 'red', name: 'three'},
{color .........}// the fourth of data are not concerned for now
]
and when i choose color:blue
, and limit 4, I want to get the data
[
{color: 'blue', name: 'four'},
{color ........},
{color ........},
{color .........}// now just care the first data
]
Have some function to achieve this?
My english is so poor, I hope the meaning is clear.
anyway, thanks!
Upvotes: 0
Views: 377
Reputation: 10918
In your specific example you can write this:
db.color.aggregate([{
$addFields : {
"rank" : { // add a field called rank to all our documents
$cond: {
if: { $eq: [ "$color", "blue" ] }, // if the color value matches "blue"
then: 0, // then we want items to be on the top
else: 1 // else we want them to be in the second part
}
}
}
}, {
$sort : {"rank" : 1} // sort ascending by our newly created "rank" field
}])
If you are using an older version of MongoDB (<3.4) that does not support $addFields yet you can instead resort to using $project instead like so:
db.color.aggregate([{
$project : {
"color": 1, // we want to retain the value of the color field
"name": 1, // the same goes for the name field
"rank" : { // add a field called rank to all our documents
$cond: {
if: { $eq: [ "$color", "blue" ] }, // if the color value matches "blue"
then: 0, // then we want items to be on the top
else: 1 // else we want them to be in the second part
}
}
}
}, {
$sort : {"rank" : 1} // sort ascending by our newly created "rank" field
}])
Upvotes: 0