如何在猫鼬中使用 match 和 groupby?

How to use match and groupby in mongoose?

我有一个这样的 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 对 return 结果进行分组,如下所示:

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

其中 sections 只是不同的字符串,而且结果应该使用 customer 过滤,这是一个 mongoose Id。我应该如何实施?

  • $match您需要的条件
  • $group by section 构造customers
  • 的数组
  • $group by null 并构造键值格式的节数组
  • $arrayToObjectsections 的键值数组转换为对象
  • $replaceRoot 将上面转换的对象替换为 root
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