我有一组数据。当我选择过滤条件时,我想查询所有的数据,把符合筛选条件的值放在查询结果的前面。
例如
[
{color: 'blue', name: 'four'},
{color: 'green', name: 'five'},
{color: 'red', name: 'one'},
{color: 'red', name: 'two'},
{color: 'red', name: 'three'}
]
当我选择color:red
并限制为 4 时,我想获取数据
[
{color: 'red', name: 'one'},
{color: 'red', name: 'two'},
{color: 'red', name: 'three'},
{color .........}// the fourth of data are not concerned for now
]
当我选择color:blue
并限制为 4 时,我想获取数据
[
{color: 'blue', name: 'four'},
{color ........},
{color ........},
{color .........}// now just care the first data
]
有什么功能可以实现这个吗?
我的英语太差了,我希望意思是清楚的。
总之感谢!
在您的具体示例中,您可以这样写:
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
}])
如果您使用的是不支持$addFields的旧版本 MongoDB (<3.4),您可以改为使用$project代替,如下所示:
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
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句