In the subdocument Mongodb array, is there any way to add a new field in each bribe

Suppose I have a document like

{
    "_id" : 5,
    "rows": [
        { "id" : "aab", "value":100},
        { "id" : "aac", "value":400},
        { "id" : "abc", "value":200},
        { "id" : "xyz", "value":300}
    ]
}

and I need to add a new key to each additional status document : 1 , and the result should look like

{
    "_id" : 5,
    "rows": [
        { "id" : "aab", "value":100, "status":1},
        { "id" : "aac", "value":400, "status":1},
        { "id" : "abc", "value":200, "status":1},
        { "id" : "xyz", "value":300, "status":1}
    ]
}

How can I do this with a single update request?

+4
source share
1 answer

Mongo operator position with $elemMatchthe problem;

The $ operator can update the first element of an array that matches several query criteria specified using the $ elemMatch () operator.

, , mongo, . rows.aac , status:1 row.aac, , :

db.collectionName.update({
  "_id": 5,
  "rows": {
    "$elemMatch": {
      "id": "abc"
    }
  }
}, {
  $set: {
    "rows.$.status": 1
  }
}, true, false) // here you insert new field so upsert true

mongo , upsert multi.

, programming code script. , cursor forEach:

db.collectionName.find().forEach(function(data) {
  for (var ii = 0; ii < data.rows.length; ii++) {
    db.collectionName.update({
      "_id": data._id,
      "rows.id": data.rows[ii].id
    }, {
      "$set": {
        "rows.$.status": 1
      }
    }, true, false);
  }
})

, mongo, , mongo bulk:

var bulk = db.collectionName.initializeOrderedBulkOp();
var counter = 0;
db.collectionName.find().forEach(function(data) {
  for (var ii = 0; ii < data.rows.length; ii++) {

    var updatedDocument = {
      "$set": {}
    };

    var setStatus = "rows." + ii + ".status";
    updatedDocument["$set"][setStatus] = 101;
    // queue the update
    bulk.find({
      "_id": data._id
    }).update(updatedDocument);
    counter++;
    //  re-initialize every 1000 update statements
    if (counter % 1000 == 0) {
      bulk.execute();
      bulk = db.collectionName.initializeOrderedBulkOp();
    }
  }

});
// Add the rest in the queue
if (counter % 1000 != 0)
  bulk.execute();
+1

Source: https://habr.com/ru/post/1584254/


All Articles