【问题标题】:how to sorting according to the value of a field? mongo如何根据字段的值进行排序?蒙哥
【发布时间】:2018-05-18 20:42:39
【问题描述】:

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

例如

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

有一些功能可以实现吗?

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

无论如何,谢谢!

【问题讨论】:

  • 你好,比利林;我可以确认您想从查询中获取四条记录,即使您的查询中只有一条颜色记录?
  • 我只想推进符合条件的结果,其他无所谓。
  • 啊,你的意思是你想查询所有的记录,但是你想获取特定颜色的记录first ie在列表的顶部?跨度>

标签: javascript database mongodb mongoose


【解决方案1】:

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

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

【讨论】:

  • 谢谢!再问一个问题,如果我不是只有两个字段,而且版本低,怎么写项目?每个字段为 1?有什么简单的方法可以自动匹配我的数据表中的所有字段?
  • 我需要一个更具体的案例来回答这个问题。您能否提供一些示例数据并说明您想要获得的具体数据?
  • 例如,我在这个表中有一些文件(姓名。年龄,城市,电话,地址,电子商城......)。如果我使用$project,我必须写"name":1,"age":1,"city":1,"phone":1, "address":1,"email": 1....... "rank": .?
  • 是的,这有点烦人。但从 MongoDB 3.4 开始,您可以改用 $addFields。
【解决方案2】:

如果您正在使用find 函数,那么您可以使用sort 函数。 如果是聚合框架,那么管道$sort 阶段。

【讨论】:

  • 官方文档有点模糊。您能根据我的问题帮助编写代码吗?
猜你喜欢
  • 2014-03-07
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多