【问题标题】:Mongoose - Custom sorting by a string field in specific orderMongoose - 按特定顺序按字符串字段自定义排序
【发布时间】:2020-09-13 17:58:53
【问题描述】:

我有一个带有一些 type 字段的模型:

const petOptions = Object.freeze({
  Dog: "Dog",
  Cat: "Cat",
  Parrot: "Parrot",
  Other: "Other",
});

const petSchema = new mongoose.Schema(
   {
      ...,
      type: {type: String, enum: petOptions, required: true},
   }
)

const Pet = mongoose.model("Pet", petSchema)

当我在该模型上运行 find 时,我需要能够按特定顺序排序,这意味着:

  • 首先是所有带有type = "Parrot" 的文档
  • 那么所有带有type = "Cat"的文档
  • 那么所有带有type = "Dog"的文档
  • 然后是所有其他文件(所有带有type = "Other" 的文档)

我可以在 JS 代码本身上做到这一点,但想知道这是否可以使用 mongoose find().sort()

Pet.find({}).sort(?)

任何帮助将不胜感激!

提前致谢

【问题讨论】:

    标签: node.js string mongodb sorting mongoose


    【解决方案1】:

    您可以使用$addFields$switch 准备一个字段,您可以在下一个聚合阶段使用$sort

    await Pet.aggregate([
        {
            $addFields: {
                sortField: {
                    $switch: {
                        branches: [
                            { case: { $eq: [ "$type", "Parrot" ] }, then: 0 },
                            { case: { $eq: [ "$type", "Cat" ] }, then: 1 },
                            { case: { $eq: [ "$type", "Dog" ] }, then: 2 },
                        ],
                        default: 3
                    }
                }
            }
        },
        {
            $sort: { sortField: 1 }
        }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 2014-02-08
      • 2017-07-30
      • 1970-01-01
      • 2023-01-21
      • 2013-06-18
      • 2012-06-02
      相关资源
      最近更新 更多