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

UPDATE Person SET Name = FirstName + ' ' + LastName

MongoDB的伪代码是:

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

当前回答

在MongoDB 4.2+版本中,更新更加灵活,因为它允许在更新、updateOne和updateMany中使用聚合管道。你现在可以使用聚合操作符转换你的文档,然后更新,而不需要显式地声明$set命令(而不是使用$replaceRoot: {newRoot: "$$ROOT"})

在这里,我们使用聚合查询从MongoDB的ObjectID“_id”字段提取时间戳,并更新文档(我不是SQL专家,但我认为SQL不提供任何自动生成的ObjectID,有时间戳,你必须自动创建该日期)

var collection = "person"

agg_query = [
    {
        "$addFields" : {
            "_last_updated" : {
                "$toDate" : "$_id"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: "$$ROOT"
        } 
    }
]

db.getCollection(collection).updateMany({}, agg_query, {upsert: true})

其他回答

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

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

在MongoDB 4.2+版本中,更新更加灵活,因为它允许在更新、updateOne和updateMany中使用聚合管道。你现在可以使用聚合操作符转换你的文档,然后更新,而不需要显式地声明$set命令(而不是使用$replaceRoot: {newRoot: "$$ROOT"})

在这里,我们使用聚合查询从MongoDB的ObjectID“_id”字段提取时间戳,并更新文档(我不是SQL专家,但我认为SQL不提供任何自动生成的ObjectID,有时间戳,你必须自动创建该日期)

var collection = "person"

agg_query = [
    {
        "$addFields" : {
            "_last_updated" : {
                "$toDate" : "$_id"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: "$$ROOT"
        } 
    }
]

db.getCollection(collection).updateMany({}, agg_query, {upsert: true})

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

对于登陆这里试图使用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);

对于活动频繁的数据库,您可能会遇到更新会影响主动更改记录的问题,因此我建议使用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/

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

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