I need to duplicate a document from my collection orders
by filtering the field cd_order
with value "7650614875".
Collection orders
look like this:
{
...
"cd_order": "7650614875"
...
}
I will copy this document more than 50 times (I will change this value in the query), so I also need to change the value from this field cd_order
from this copied document to another value, so I though by converting into int
and then use the function inc
to increment 1 and then converting back to string
.
I tried the query below but only the copy ocorrued, the rest didn’t work:
var copy = db.orders.findOne({ cd_order: "7650614875" }, { _id: 0 });
for (var i = 0; i< 3; i++){
db.orders.insert(copy);
{ $convert: { input: $string, to: "int" } }
{ $inc: { "cd_order" : 1 } }
{ $convert: { input: $int, to: "string" } }
}
How can I duplicate this document, increment 1 into field cd_order
to not be the same as the previous one, and also to print all new cd_order
at the end?
Print example:
cd_order: 7650614875, 7650614876, 7650614877, 76506148758, ...
2
Answers
I was able to duplicate to convert the value and increment before duplicating the document, it worked well:
I was also able to print all values using this query:
You can use
$range
to generate an array of increment.$unwind
the array to add tocd_order
and$merge
to insert/update into the collectionMongo Playground