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
?
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?
– nbkhope
Yes @nbkhope, using the operator
$first
in other fields (if not array)– BrTkCa