[英]How do I update an array from MongoDB document that match a certain value?
I'm a new mongoDB user, and I'm confused on how to update my document. 我是mongoDB的新用户,我对如何更新文档感到困惑。
I have this document: 我有这个文件:
"_id" : ObjectId("5674c86aba97df0800995da7"),
"role" : "tutor",
"schools" : [
"CHIJ Our Lady Of Good Counsel",
"Nanyang Technological University"]
And I'd like to update the schools array from this document that matches a certain value from a var. 我想从此文档中更新与数组中某个值匹配的schools数组。 I've tried like this:
我已经试过像这样:
var schools = [{ "name": "Nanyang Technological University (NTU)", "value": "nanyang-technological-university-(ntu)" }];
db.getCollection('clients').update(
// query
{
"schools" : schools.name
},
// update
{
$set:{"schools":[schools.value]}
},
// options
{
"multi" : true, // update only one document
"upsert" : false // insert a new document, if no existing document match the query
}
);
But of course, it's not working. 但是,当然,它不起作用。 Can anyone help me with this?
谁能帮我这个? Thanks!
谢谢!
I need the document to be displaying this value after update: 我需要文档在更新后显示此值:
"_id" : ObjectId("5674c86aba97df0800995da7"),
"role" : "tutor",
"schools" : [
"CHIJ Our Lady Of Good Counsel",
"nanyang-technological-university-(ntu)"]
You could make use of the $
operator: 您可以使用
$
运算符:
schools
variable, schools
变量中的每个项目, find
records, with the corresponding name
in the schools
array field. schools
数组字段中find
具有相应name
记录。 $set
the new value
at the position of the matched name
using the $
positional operator. $set
使用$
位置运算符在匹配name
的位置$set
新value
。 code: 码:
var schools=[{"name":"Nanyang Technological University",
"value":"nanyang-technological-university-(ntu)"}];
schools.forEach(function(i){
db.clients.update({"schools.name":i.name},
{$set:{"schools.$":i.value}},
{"multi":true})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.