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

UPDATE Person SET Name = FirstName + ' ' + LastName

MongoDB的伪代码是:

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

当前回答

Update()方法将聚合管道作为参数,如

db.collection_name.update(
  {
    // Query
  },
  [
    // Aggregation pipeline
    { "$set": { "id": "$_id" } }
  ],
  {
    // Options
    "multi": true // false when a single doc has to be updated
  }
)

可以使用聚合管道使用现有值设置或取消设置字段。

注意:使用带字段名的$来指定要读取的字段。

其他回答

你应该迭代。针对您的具体情况:

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

显然,自从MongoDB 3.4以来,有一种方法可以有效地做到这一点,请参阅styvane的答案。


过时的答案如下

您还不能在更新中引用文档本身。您需要遍历文档并使用函数更新每个文档。请参阅下面的示例,或者服务器端eval()的示例。

Update()方法将聚合管道作为参数,如

db.collection_name.update(
  {
    // Query
  },
  [
    // Aggregation pipeline
    { "$set": { "id": "$_id" } }
  ],
  {
    // Options
    "multi": true // false when a single doc has to be updated
  }
)

可以使用聚合管道使用现有值设置或取消设置字段。

注意:使用带字段名的$来指定要读取的字段。

(我本想把这篇文章作为评论,但我做不到)

对于登陆这里试图使用c#驱动程序更新文档中的另一个字段的任何人… 我不知道如何使用任何UpdateXXX方法及其相关重载,因为它们将UpdateDefinition作为参数。

// we want to set Prop1 to Prop2
class Foo { public string Prop1 { get; set; } public string Prop2 { get; set;} } 

void Test()
{ 
     var update = new UpdateDefinitionBuilder<Foo>();
     update.Set(x => x.Prop1, <new value; no way to get a hold of the object that I can find>)
}

作为一种变通方法,我发现可以在IMongoDatabase (https://docs.mongodb.com/manual/reference/command/update/#dbcmd.update)上使用RunCommand方法。

var command = new BsonDocument
        {
            { "update", "CollectionToUpdate" },
            { "updates", new BsonArray 
                 { 
                       new BsonDocument
                       {
                            // Any filter; here the check is if Prop1 does not exist
                            { "q", new BsonDocument{ ["Prop1"] = new BsonDocument("$exists", false) }}, 
                            // set it to the value of Prop2
                            { "u", new BsonArray { new BsonDocument { ["$set"] = new BsonDocument("Prop1", "$Prop2") }}},
                            { "multi", true }
                       }
                 }
            }
        };

 database.RunCommand<BsonDocument>(command);

我尝试了上面的解决方案,但我发现它不适合大量数据。然后我发现了流的特性:

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
    })
})