[英]How do I update nested MongoDB object
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.我现在已经坚持了 6 个小时......我如何更新内部对象内部的字段和 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.
就像我只想更改“频率”和“状态”字段,但我只想更改“_id”等于查询的字段。
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您的查询运行良好,请在此MongoPlayground上尝试
req.body.inputId
has to be an ObjectId to match the _id
in nouns
req.body.inputId
必须是一个 ObjectId 以匹配nouns
中的_id
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.我想通了...感谢 AlexisG 给我的线索,我需要一个 ObjectId 而不仅仅是来自 ObjectId 括号内的字符串 ID。
Solution was to declare at the start of the js file: const ObjectId = require('mongodb').objectID解决办法是在js文件的开头声明:const ObjectId = require('mongodb').objectID
and then in arrayFilters:[{"element._id": ObjectId(req.body.inputId)}]然后在 arrayFilters:[{"element._id": ObjectId(req.body.inputId)}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.