【问题标题】:Sorting on Multiple fields mongo DB with mongooes. Does the order of field affect the query results?使用 mongoose 对多个字段 mongoDB 进行排序。字段顺序是否影响查询结果?
【发布时间】:2020-11-24 04:42:17
【问题描述】:

我有一个列表文档“测试”,格式如下: { _id: 1, name: 'Jony Tan', age: 10} and _id is index

db.getCollection('Test').find({}, { name: 1, age: 1}).sort({ name: 1, age: 1})
and
db.getCollection('Test').find({}, { name: 1, age: 1}).sort({ age: 1, name: 1})

让我看看查询结果是一样的(先排序“name”,再排序“age”)。

那么,如何使用“age”第一和“name”第二的多重排序?

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    你可以做多个排序操作,像这样,

    • 名字第一,年龄第二
    db.getCollection('Test').find({}, { name: 1, age: 1})
      .sort({name: 1})
      .sort({age: 1});
    
    • 年龄第一,名字第二
    db.getCollection('Test').find({}, { name: 1, age: 1})
      .sort({age: 1});
      .sort({name: 1})
    

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2017-06-03
      相关资源
      最近更新 更多