2015-10-15 20 views
1

我有一个集合,看起来像这样:添加字段集合如果不存在

{'flags': {'flag_1': True, 'flag_2': False: 'flag_3': True} 
    'other_data': {....}} 

在一个单一的操作,我想标志的列表添加到现有的标志。如果国旗已经存在,我想保留它的价值,否则它应该是False。

例如添加[ 'flag_3', 'flag_4']后,收集应该是这样的。

{'flags': {'flag_1': True, 'flag_2': False: 'flag_3': True, 'flag_4':False} 
    'other_data': {....}} 

感谢

回答

1

可以使用Bulk API与一些逻辑简化您的更新,以获得其需要添加标志的方式。事情是这样的:

var bulk = db.collection.initializeOrderedBulkOp(), 
    counter = 0, 
    flagList = ['flag_3', 'flag_4']; 


db.collection.find().forEach(function(doc){ 
    var existingFlags = Object.keys(doc.flags), // get the existing flags in the document 
     newFlags = flagList.filter(function(n) { // use filter to return an array of flags which do not exist 
      return existingFlags.indexOf(n) < 0; 
     }), 
     update = newFlags.reduce(function(obj, k) { // set the update object 
      obj["flags."+ k] = false; 
      return obj; 
     }, { }); 

    bulk.find({ "_id": doc._id }).updateOne({ 
     "$set": update 
    }); 

    counter++; 
    if (counter % 1000 == 0) { 
     // Execute per 1000 operations and re-initialize every 1000 update statements 
     bulk.execute(); 
     bulk = db.collection.initializeOrderedBulkOp(); 
    } 
}) 

// Clean up queues 
if (counter % 1000 != 0){ 
    bulk.execute(); 
} 
相关问题