Reputation: 179
Is there any way to duplicate a document during aggregation in mongo? For example, I've got a "Person" schema that looks like that:
Person:
{
_id: ObjectId,
fullName: string,
matches: number
}
I want to make an aggregation that returns all the persons and duplicates each person's document by the number of his matches
.
for example for this collection:
[{
_id: 1,
fullName: "John Doe",
matches: 1
},
{
_id: 2,
fullName: "Bla Bla",
matches: 2
}]
The result will be:
[{
_id: 1,
fullName: "John Doe",
matches: 1
},
{
_id: 2,
fullName: "Bla Bla",
matches: 2
},
{
_id: 2,
fullName: "Bla Bla",
matches: 2
}]
I know that I can add fields to the documents during the aggregation but didn't found anything about adding documents.
Upvotes: 3
Views: 1008
Reputation: 36104
0
and end at matches
number, it will return array of current root documentmatches
arraymatches
object to rootdb.collection.aggregate([
{
$project: {
matches: {
$map: {
input: { $range: [0, "$matches"] },
in: "$$ROOT"
}
}
}
},
{ $unwind: "$matches" },
{ $replaceRoot: { newRoot: "$matches" } }
])
Upvotes: 2