首页 文章

使用另一个字段的值更新MongoDB字段

提问于
浏览
274

在MongoDB中,是否可以使用另一个字段中的值更新字段的值?等效的SQL将是这样的:

UPDATE Person SET Name = FirstName + ' ' + LastName

而MongoDB伪代码将是:

db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );

6 回答

  • 222

    执行此操作的最佳方法是使用聚合框架来计算新字段 .

    MongoDB 3.4

    最有效的解决方案是在MongoDB 3.4中使用$addFields$out聚合管道运算符 .

    db.collection.aggregate(
        [
            { "$addFields": { 
                "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
            }},
            { "$out": "collection" }
        ]
    )
    

    请注意,此 does not update your collection but instead replace the existing collection or create a new one. 也适用于需要 "type casting" you will need client side processing, 的更新操作,并且根据操作,您可能需要使用 find() 方法而不是 .aggreate() 方法 .

    MongoDB 3.2和3.0

    我们这样做的方法是$project我们的文档并使用$concat字符串聚合运算符来返回连接的字符串 . 然后,您可以从那里迭代光标并使用$set update运算符使用批量操作将新字段添加到文档中,以实现最高效率 .

    聚合查询:

    var cursor = db.collection.aggregate([ 
        { "$project":  { 
            "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
        }}
    ])
    

    MongoDB 3.2或更新版本

    从这里,你需要使用bulkWrite方法 .

    var requests = [];
    cursor.forEach(document => { 
        requests.push( { 
            'updateOne': {
                'filter': { '_id': document._id },
                'update': { '$set': { 'name': document.name } }
            }
        });
        if (requests.length === 500) {
            //Execute per 500 operations and re-init
            db.collection.bulkWrite(requests);
            requests = [];
        }
    });
    
    if(requests.length > 0) {
         db.collection.bulkWrite(requests);
    }
    

    MongoDB 2.6和3.0

    在此版本中,您需要使用现已弃用的Bulk API及其associated methods .

    var bulk = db.collection.initializeUnorderedBulkOp();
    var count = 0;
    
    cursor.snapshot().forEach(function(document) { 
        bulk.find({ '_id': document._id }).updateOne( {
            '$set': { 'name': document.name }
        });
        count++;
        if(count%500 === 0) {
            // Excecute per 500 operations and re-init
            bulk.execute();
            bulk = db.collection.initializeUnorderedBulkOp();
        }
    })
    
    // clean up queues
    if(count > 0) {
        bulk.execute();
    }
    

    MongoDB 2.4

    cursor["result"].forEach(function(document) {
        db.collection.update(
            { "_id": document._id }, 
            { "$set": { "name": document.name } }
        );
    })
    
  • 40

    对于具有高活动性的数据库,您可能会遇到更新影响主动更改记录的问题,因此我建议使用 snapshot()

    db.person.find().snapshot().forEach( function (hombre) {
        hombre.name = hombre.firstName + ' ' + hombre.lastName; 
        db.person.save(hombre); 
    });
    

    http://docs.mongodb.org/manual/reference/method/cursor.snapshot/

  • 9

    这就是我们想出的将一个字段复制到另一个字段~150_000条记录的内容 . 它花了大约6分钟,但仍然比实例化和迭代相同数量的ruby对象的资源密集程度要低得多 .

    js_query = %({
      $or : [
        {
          'settings.mobile_notifications' : { $exists : false },
          'settings.mobile_admin_notifications' : { $exists : false }
        }
      ]
    })
    
    js_for_each = %(function(user) {
      if (!user.settings.hasOwnProperty('mobile_notifications')) {
        user.settings.mobile_notifications = user.settings.email_notifications;
      }
      if (!user.settings.hasOwnProperty('mobile_admin_notifications')) {
        user.settings.mobile_admin_notifications = user.settings.email_admin_notifications;
      }
      db.users.save(user);
    })
    
    js = "db.users.find(#{js_query}).forEach(#{js_for_each});"
    Mongoid::Sessions.default.command('$eval' => js)
    
  • 120

    显然,自MongoDB 3.4以来,有一种方法可以有效地执行此操作,请参见styvane's answer .


    Obsolete answer below

    您还不能在更新中引用文档本身 . 您需要遍历文档并使用函数更新每个文档 . 有关示例,请参阅this answer;有关服务器端 eval() ,请参阅this one .

  • 101

    你应该迭代 . 对于您的具体情况:

    db.person.find().snapshot().forEach(
        function (elem) {
            db.person.update(
                {
                    _id: elem._id
                },
                {
                    $set: {
                        name: elem.firstname + ' ' + elem.lastname
                    }
                }
            );
        }
    );
    
  • 2

    我尝试了上述解决方案,但我发现它不适合大量数据 . 然后我发现了流功能:

    MongoClient.connect("...", function(err, db){
        var c = db.collection('yourCollection');
        var s = c.find({/* your query */}).stream();
        s.on('data', function(doc){
            c.update({_id: doc._id}, {$set: {name : doc.firstName + ' ' + doc.lastName}}, function(err, result) { /* result == true? */} }
        });
        s.on('end', function(){
            // stream can end before all your updates do if you have a lot
        })
    })
    

相关问题