I'm a new mongoDB user, and I'm confused on how to update my document.
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. 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, find
records, with the corresponding name
in the schools
array field. $set
the new value
at the position of the matched name
using the $
positional operator. 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})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.