如何根据字段的值进行排序?蒙戈

比利·林

我有一组数据。当我选择过滤条件时,我想查询所有的数据,把符合筛选条件的值放在查询结果的前面。

例如

[
    {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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何根据列的值对Laravel中的行进行排序?

如何根据树的值对树图进行排序?

如何根据Array字段的长度对文档进行排序

SQL如何根据“顺序”字段对子行进行排序?

如何根据Scala中的对象字段对列表对象进行排序?

如何根据条件对熊猫数据框的行值进行排序?

根据值对组进行排序

如何根据值对地图进行排序

如何根据lucene中的字段对文档进行排序?

如何根据字典值对列表进行排序?

如何根据数组值对HTML元素进行排序

如何根据POJO的特定字段值对集合进行排序?

根据不同的字段和值进行排序

如何在流星+蒙戈中实现多对多集合,以便所有可能的字段都可以搜索和/或排序该集合?

如何在lua中根据多个值对表进行排序?

如何持久地将不同的值从 collectionA 映射到 collectionB?流星蒙戈

JAVA:如何根据字段对列表进行排序

如何根据重复字段对对象列表进行排序?

根据对象字段的分组对列表进行排序,根据组中的最大值进行排序

如何根据列值对列表进行排序

如何根据列表值对元组进行排序?

根据组对值进行排序

如何根据嵌套值对对象进行排序

如何根据相应的 ascii 值对列表进行排序?

如何根据字段偏好对elasticsearch结果集进行排序

如何根据内部值对 CSV 字符串进行排序?

如何根据引用值进行过滤?姜戈

如何根据子字段的值对对象数组进行排序?

如何根据多个因素对 Scala 中的“映射”值进行排序?