How to reverse the $unwind operation on Mongodb 3.4?

Asked

Viewed 118 times

1

Imagine a collection of products:

db.produtos.find()
[
  {
    _id: "produto01",
    cores: ["preto", "branco", "ouro"]
  },
  {
    _id: "produto02",
    cores: ["branco", "ouro"]
  }
]

Each product has a field called colors, which is a list of strings. Using the $unwind in the color field results in the following:

db.produtos.aggregate([ { $unwind: "$cores" } ])
[
  {
    _id: "produto01",
    cores: "preto"
  },
  {
    _id: "produto01",
    cores: "branco"
  },
  {
    _id: "produto01",
    cores: "ouro"
  },
  {
    _id: "produto02",
    cores: "branco"
  },
  {
    _id: "produto02",
    cores: "ouro"
  }
]

How do you reverse this operation? That is, go from the above result back to the original, after doing $unwind?

1 answer

1


Using $group with $push will regroup the array to the object, thus:

db.produtos.aggregate([{
        $unwind: "$cores"
    },
    {
        "$group": {
            "_id": "$_id",
            "cores": {
                $push: "$cores"
            }
        }
    }
])
  • If each product had more fields, then we would have to explicitly indicate each one in the value of $group, otherwise they would not appear?

  • 1

    Yes @nbkhope, using the operator $first in other fields (if not array)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.