Home > database >  How can I $group, with same structure of data and just to create a unique field group?
How can I $group, with same structure of data and just to create a unique field group?

Time:10-06

I have a mongodbdb collection which has

{ _id, field: { product: { _id } }

what I need is to $group by product so that _id will be unique (does not have duplicates), but at the same time, preserve the data structure?

What I did: None so far (just reading the Mongodb docs on how to do this)

CodePudding user response:

The $group stage alters the document structure, so you'll need to add another stage after it to convert the document back to the original structure, here is an example on how to do it by saving the first document for each product _id then replace the root with that object:

db.collection.aggregate([
  {
    $group: {
      _id: "$field.product._id",
      firstRoot: {
        $first: "$$ROOT"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$firstRoot"
    }
  }
])

Mongo Playground

  • Related