2015-10-04 46 views

回答

0

要更新指定索引的seats數組中,你需要遍歷該索引的每個元素的每個元素,並使用$inc運營商"bulk"操作來增加價值。

var bulkOp = db.collection.initializeOrderedBulkOp(); 
var fromIndex = 1 
var toIndex = 3 

db.collection.find({ '_id': 1 }).forEach(function(doc) { 
    var seats = doc.seats; 
    for(var index = fromIndex; index <= toIndex; index++) { 
     bulkOp.find({ '_id': doc._id, 'seats': seats[index] }) 
       .updateOne({ '$inc': { 'seats.$':1 } }); 
bulkOp.execute(); 

然後db.collection.find({ '_id': 1 })產生

{ "_id" : 1, "seats" : [ 80, 86, 91, 96 ] } 
2

你可以嘗試和兩個$inc更新操作的組合dot notation通過從零開始的訪問席位數組的元素索引位置並將它們加1。下面update()操作使用$inc操作者被1至從位置1座椅陣列增加到"_id": 1字段的3位:

db.collection.update(
    { "_id": 1 }, 
    { 
     "$inc": { 
      "seats.1": 1, 
      "seats.2": 1, 
      "seats.3": 1 
     } 
    }  
); 
相關問題