【问题标题】:MongoDB Sort certain Documents to top firstMongoDB首先将某些文档排序到顶部
【发布时间】:2020-03-03 21:47:16
【问题描述】:

假设我有以下收藏

Collection = [
    {name: 'Ann'},
    {name: 'Bob'},
    {name: 'Cecil'},
    {name: 'KEY: John'},
    {name: 'KEY: Cecil'},
    {name: 'Susan'},
    {name: 'Zack'}
];

有什么方法可以在MongoDB 中使用sort,这样我就可以让所有Documentsname 字段以KEY: 开头,然后首先返回?然后我希望将 Collection 的其余部分按当前状态排序。

Collection = [
        {name: 'KEY: John'},
        {name: 'KEY: Cecil'},
        {name: 'Ann'},
        {name: 'Bob'},
        {name: 'Cecil'},
        {name: 'Susan'},
        {name: 'Zack'}
    ];

据我所知,无法在 MongoDB 中进行自定义排序。如果没有,是否有一种简单的方法可以在 JS 中使用 underscore 或其他一些库来执行此操作。我更喜欢这里接受的答案Sort an array to have specific items first in the array 必须构建另一个数组。

有什么想法吗?

【问题讨论】:

  • 也许是带有 array.sort 的自定义比较函数?

标签: javascript arrays mongodb sorting


【解决方案1】:

您可以使用$addFields 来评估您的收藏将作为排序依据的新字段。 $indexOfBytes 运算符可用于确定字符串是否以 KEY 开头:

db.collection.aggregate([
    {
        $addFields: {
            startsWithKey: { $eq: [ { $indexOfBytes: [ "$name", "KEY", 0 ] } ]}
        }
    },
    {
        $sort: {
            startsWithKey: -1
        }
    }
])

Mongo Playground

【讨论】:

  • 谢谢!是否可以在没有聚合的情况下做到这一点?
  • 不,您必须使用$addFields,它只能在,aggregate() 下使用。有问题吗?
  • 本质上不是问题,只是聚合是我正在使用的框架中的一个痛点(Meteor)
猜你喜欢
  • 2019-06-16
  • 2023-03-13
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
相关资源
最近更新 更多