Search code examples
mongodbmongoosemongodb-queryaggregation-frameworkmongoose-schema

How to use match and groupby in mongoose?


I have a customerDocument schema like this:

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 }
);

I need the return result to be grouped based on the section something like this:

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

where the sections are just different strings and also the results should be filtered with the customer which is a mongoose Id. How should I implement this?


Solution

    • $match your required conditions
    • $group by section and construct array of customers
    • $group by null and construct array of sections in key-value format
    • $arrayToObject convert key-value array of sections to object
    • $replaceRoot to replace above converted object to 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