【问题标题】:How to use match and groupby in mongoose?如何在猫鼬中使用 match 和 groupby?
【发布时间】:2021-07-29 21:33:13
【问题描述】:

我有一个这样的 customerDocument 架构:

const customerDocumentSchema = new mongoose.Schema(
  {
    title: { type: String, required: true },
    section: { type: String },
    description: { type: String, required: true },
    customer: { type: mongoose.Schema.Types.ObjectId },
    documentKey: { type: String },
  },
  { timestamps: true }
);

我需要根据section 对返回结果进行分组,如下所示:

[
  section1:[{title:'',description:'',customer:'',documentKey:''},{},{}...],
  section2:[{title:'',description:'',customer:'',documentKey:''},{},{}....],
  sectionN:[....]
]

sections 只是不同的字符串,结果也应该用 customer 过滤,这是一个猫鼬 ID。我应该如何实现这个?

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework mongoose-schema


    【解决方案1】:
    • $match您需要的条件
    • $group by section 并构造 customers 的数组
    • $group by null 并以键值格式构造部分数组
    • $arrayToObjectsections 的键值数组转换为对象
    • $replaceRoot 将上面转换的对象替换为根
    let customer_id = mongoose.Types.ObjectId(customer);
    let result = await SchemaModelName.aggregate([
      { $match: { customer: 1 } },
      {
        $group: {
          _id: "$section",
          customers: { $push: "$$ROOT" }
        }
      },
      {
        $group: {
          _id: null,
          sections: { $push: { k: "$_id", v: "$customers" } }
        }
      },
      { $replaceRoot: { newRoot: { $arrayToObject: "$sections" } } }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多