使用另一个字段的值更新MongoDB字段
在MongoDB中,是否可以使用另一个字段的值更新字段的值?等效的SQL类似于:使用另一个字段的值更新MongoDB字段,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,在MongoDB中,是否可以使用另一个字段的值更新字段的值?等效的SQL类似于: UPDATE Person SET Name = FirstName + ' ' + LastName MongoDB伪代码是: db.person.update( {}, { $set : { name : firstName + ' ' + lastName } ); 显然,自从MongoDB 3.4以来,有一种方法可以有效地实现这一点,请参见 下面过时的答案 您还不能在更新中引用文档本身。您需要遍历文档
UPDATE Person SET Name = FirstName + ' ' + LastName
MongoDB伪代码是:
db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );
显然,自从MongoDB 3.4以来,有一种方法可以有效地实现这一点,请参见
下面过时的答案
您还不能在更新中引用文档本身。您需要遍历文档并使用函数更新每个文档。有关示例,请参见,或者有关服务器端
eval()
的信息,请参见。针对您的具体情况:
db.person.find().snapshot().forEach(
function (elem) {
db.person.update(
{
_id: elem._id
},
{
$set: {
name: elem.firstname + ' ' + elem.lastname
}
}
);
}
);
对于具有高活动性的数据库,您可能会遇到更新会影响动态更改记录的问题,因此我建议使用snapshot()
db.person.find().snapshot().forEach( function (hombre) {
hombre.name = hombre.firstName + ' ' + hombre.lastName;
db.person.save(hombre);
});
我尝试了上述解决方案,但发现它不适合大量数据。然后我发现了流特征:
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
})
})
最好的方法是在4.2+版本中,它允许在更新文档和、或集合方法中使用聚合管道。请注意,后者在大多数(如果不是所有的话)语言驱动程序中都被弃用 MongoDB 4.2+ 版本4.2还引入了pipeline阶段操作符,它是的别名。我将在这里使用
$set
,因为它映射了我们正在努力实现的目标
db.collection.<update method>(
{},
[
{"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
]
)
请注意,此不会更新您的集合,而是替换现有集合或创建一个新集合。此外,对于需要“类型转换”的更新操作,您将需要客户端处理,并且根据操作的不同,您可能需要使用find()
方法,而不是.aggreate()
方法
MongoDB 3.2和3.0
我们这样做的方法是将文档合并,并使用字符串聚合操作符返回连接的字符串。
我们从那里开始,然后迭代光标并使用update操作符,使用批量操作将新字段添加到文档中,以获得最大效率
聚合查询:
MongoDB 3.2或更新版本
因此,您需要使用该方法
MongoDB 2.6和3.0
在此版本中,您需要使用现在已弃用的API及其
MongoDB 2.4
下面是我们为15万条记录将一个字段复制到另一个字段的结果。这花费了大约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)
对此,3.6版中不推荐使用快照功能,如下所示。因此,在3.6及以上版本上,可以通过以下方式执行操作:
db.person.find().forEach(
function (elem) {
db.person.update(
{
_id: elem._id
},
{
$set: {
name: elem.firstname + ' ' + elem.lastname
}
}
);
}
);
启动
Mongo 4.2
,可以接受聚合管道,最终允许基于另一个字段更新/创建字段:
// { firstName: "Hello", lastName: "World" }
db.collection.update(
{},
[{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }],
{ multi: true }
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
- 第一部分是匹配查询,过滤要更新的文档(在本例中是所有文档)
- 第二部分
是更新聚合管道(注意方括号表示使用聚合管道)。是一个新的聚合运算符和[{$set:{name:{…}}]
的别名$addFields
- 不要忘记
,否则只会更新第一个匹配的文档{multi:true}
update
、updateOne
和updateMany
中使用聚合管道。您现在可以使用聚合操作符转换文档,然后进行更新,而无需明确说明$set
命令(我们使用$replaceRoot:{newRoot:$$ROOT}
)
在这里,我们使用聚合查询从MongoDB的ObjectID“\u id”字段提取时间戳并更新文档(我不是SQL专家,但我认为SQL不提供任何自动生成的带有时间戳的ObjectID,您必须自动创建该日期)
(我本想将此作为评论发布,但不能)
对于任何试图使用c#driver文档中的另一个字段来更新一个字段的人。。。
我不知道如何使用任何updatexx
方法及其相关重载,因为它们将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>)
}
这在今天仍然有效吗?@ChristianEngel:看起来是这样。我在MongoDB文档中找不到任何提到在
更新操作中引用当前文档的内容。仍然没有解决。它在2017年4月仍然有效吗?或者已经有新的功能可以做到这一点吗?@Kim它看起来仍然有效。a此外,@niels van der rest在2013年指出的问题仍然处于打开状态
。这不再是一个有效的答案,请查看@styvane answer如果其他用户在您的find()和save()之间更改了文档会发生什么情况?正确,但字段之间的复制不应要求事务是原子的。重要的是要注意,save()
完全替换文档。应使用update()
。如何使用db.person.update({id:elem.\id},{$set:{name:elem.firstname+''+elem.lastname})
我创建了一个名为create_guid
的函数,在使用forEach
进行迭代时,该函数仅为每个文档生成唯一的guid(即,在update
语句中使用mutli=true
即可为所有文档生成相同的guid)。这个答案对我来说非常有效。+1这有什么不同吗?更新活动会阻止蒸汽吗?你有任何参考资料吗?Mongo文档非常差。如果其他用户在find()和save()之间编辑此人,会发生什么情况?我有一个例子,可以对同一个对象进行多个调用,根据它们的当前值更改它们。第二个例子
cursor["result"].forEach(function(document) {
db.collection.update(
{ "_id": document._id },
{ "$set": { "name": document.name } }
);
})
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)
db.person.find().forEach(
function (elem) {
db.person.update(
{
_id: elem._id
},
{
$set: {
name: elem.firstname + ' ' + elem.lastname
}
}
);
}
);
// { firstName: "Hello", lastName: "World" }
db.collection.update(
{},
[{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }],
{ multi: true }
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
var collection = "person"
agg_query = [
{
"$addFields" : {
"_last_updated" : {
"$toDate" : "$_id"
}
}
},
{
$replaceRoot: {
newRoot: "$$ROOT"
}
}
]
db.getCollection(collection).updateMany({}, agg_query, {upsert: true})
// 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>)
}
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);