如何在猫鼬中使用匹配和分组?

时间:2021-05-07 14:56:25

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

我有一个像这样的 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 进行过滤,content_tag 是一个猫鼬 ID。我应该如何实施?

1 个答案:

答案 0 :(得分: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

相关问题