在MongoDB中使用变量作为文件名时,可以在嵌入式文档上使用'$ set'吗? [英] Can I use '$set' on embedded document when use variable as filed name in MongoDB?
本文介绍了在MongoDB中使用变量作为文件名时,可以在嵌入式文档上使用'$ set'吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用'$ set'更新嵌入的文档,但是该字段是变量.
I want to use '$set' to update an embedded document, but the field is a variable.
说我有一个像这样的文件:
Say I have a document like:
{'_id': ObjectID,
'people': {
'A': {'age': 20}
}
}
现在,我想向people
添加一个新人.我可以使用$set: {'people.B':{'age': 25}
,但是如果名称(而不是B)是变量怎么办?
Now I want to add a new person to people
. I can use $set: {'people.B':{'age': 25}
, but what if the name(instead B) is a variable?
我正在使用Node.js 5.1和'mongodb'驱动程序.
I am using Node.js 5.1 and 'mongodb' driver.
推荐答案
您需要使用[]
运算符动态构建查询.
You need to build your query dynamically using the []
operator.
var b = 'B';
var update = {};
update['people.' + b] = { 'age': 25 };
db.collection.update({}, { '$set': update })
这篇关于在MongoDB中使用变量作为文件名时,可以在嵌入式文档上使用'$ set'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文