I have been stuck on this for 6 hours now... How do I update a field inside an object inside and element that is inside another object in MongoDB.
So I have a collection of users, each user is one document which contains arrays of objects. These objects have fields that i want to be able to change. Like i want to change just the "frequency" and "status" field but i want to change only the one with an "_id" equal to a query.
I've tried
db.collections.users.updateOne(
{},
{$set: {"nouns.$[element].status": 3}},
{multi: true,
arrayFilters: [{"element._id": req.body.inputId}]}
);
Plus a lot of other things.
{
"_id" : ObjectId("5f7d8490c1842471c6bcea42"),
"username" : "eric@mail.com",
"nouns" : [
{
"_id" : ObjectId("5f7d849cc1842471c6bcea43"),
"word" : "die Sonne",
"timeStamp" : ISODate("2020-10-07T09:04:28.436Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84a8c1842471c6bcea45"),
"word" : "das Wetter",
"timeStamp" : ISODate("2020-10-07T09:04:40.940Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84afc1842471c6bcea47"),
"word" : "der Apfel",
"timeStamp" : ISODate("2020-10-07T09:04:47.403Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84b9c1842471c6bcea49"),
"word" : "das Maedchen",
"timeStamp" : ISODate("2020-10-07T09:04:57.388Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84c8c1842471c6bcea4b"),
"word" : "das Auto",
"timeStamp" : ISODate("2020-10-07T09:05:12.036Z"),
"frequency" : 0,
"status" : 0
}
],
"verbs" : [],
"adjectives" : [],
"others" : [],
"salt" : "*****",
"hash" : "*****",
"__v" : 5
}
Your query work well, try it on this MongoPlayground
req.body.inputId
has to be an ObjectId to match the _id
in nouns
I figured it out... Thanks to AlexisG for giving me the clue that I needed an ObjectId and not just a string ID from inside the ObjectId brackets.
Solution was to declare at the start of the js file: const ObjectId = require('mongodb').objectID
and then in arrayFilters:[{"element._id": ObjectId(req.body.inputId)}]
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.