Home > Net >  How to duplicate a document constant times in mongodb aggregation?
How to duplicate a document constant times in mongodb aggregation?

Time:09-29

I'm looking for a way that I can duplicate records while adding an additional property into each of them.

This is how a simplified version of my problem looks like,

Considering a collection like:

[
 { name: "john" },
 { name: "doe" }
]

Imaging I have an array of items: ['cake', 'orange'] and I'm expecting an output like below.

[
 { name: "john", item: "cake" },
 { name: "doe", item: "cake" },
 { name: "john", item: "orange" },
 { name: "doe", item: "orange"}
]

Basically, each object has been repeated to meet all combinations in the items array. Also, the order matters, each item has to be repeated with all objects before going to the next item.

CodePudding user response:

You can try this:

  Model.aggregate([
  {
    $project: {name: 1, item: ['cake', 'orange']},
  },
  {$unwind:"$item"}
]);
  • Related