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

时间:2017-12-05 08:44:37

标签: javascript database mongodb mongoose

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

例如

[
    {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
]

有一些功能来实现这个目标吗?

我的英语太差了,我希望意思很清楚。

无论如何,谢谢!

2 个答案:

答案 0 :(得分:1)

如果您使用find功能,则可以使用sort功能。 如果是聚合框架,那么管道$sort阶段。

答案 1 :(得分:0)

在您的具体示例中,您可以写下:

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
}])

如果您使用的旧版MongoDB(<3.4)不支持$addFields,您可以改为使用$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
}])