Home > OS >  How to duplicate a document in MongoDB and increment a value in another field?
How to duplicate a document in MongoDB and increment a value in another field?

Time:01-28

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, ...

CodePudding user response:

You can use $range to generate an array of increment. $unwind the array to add to cd_order and $merge to insert/update into the collection

db.collection.aggregate([
  {
    "$match": {
      "cd_order": "7650614875"
    }
  },
  {
    $set: {
      inc: {
        "$range": [
          0,
          51,
          1
        ]
      }
    }
  },
  {
    "$unwind": "$inc"
  },
  {
    $set: {
      cd_order: {
        $toString: {
          $add: [
            {
              "$toLong": "$cd_order"
            },
            "$inc"
          ]
        }
      },
      "inc": "$$REMOVE",
      _id: "$$REMOVE"
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "cd_order",
      "whenMatched": "merge",
      "whenNotMatched": "insert"
    }
  }
])

Mongo Playground

CodePudding user response:

I was able to duplicate to convert the value and increment before duplicating the document, it worked well:

var copy = db.orders.findOne({ cd_order: "7650614877" }, { _id: 0 });
for (var i = 0; i < 100; i  ) {
    copy.cd_order = (parseInt(copy.cd_order)   1).toString();
    db.orders.insert(copy);
}

I was also able to print all values using this query:

var orders = db.orders.find({ "nm_ancestor": {$eq: "Luigi D'arpino"} }, { "cd_order": 1 });
var ordersString = "";
orders.forEach(function(order) {
    if(ordersString.length>0) ordersString  = ", ";
    ordersString  = order.cd_order;
});
print("cd_order: "   ordersString);
  • Related