【发布时间】:2020-05-20 08:42:45
【问题描述】:
如何使用它在帖子数组中的 id 更新某些对象,例如使用它的 id 更改帖子中的第一个对象
{
"_id" : ObjectId("5e3929127b0a7599f0a33b90"),
"posts" : [
{
"title" : "title",
"desc" : "body",
"id" : ObjectId("5e396faeac120790c4561f4b")
},
{
"title" : "title2",
"desc" : "body2",
"id" : ObjectId("5e396faeac120790c4561x2t")
}
],
"name" : "jarvis",
"email" : "jarvis@yahoo.com",
"password" : "123",
"__v" : 0
}
变成这样
{
"_id" : ObjectId("5e3929127b0a7599f0a33b90"),
"posts" : [
{
"title" : "new title",
"desc" : "new body",
"id" : ObjectId("5e396faeac120790c4561f4b")
},
{
"title" : "title2",
"desc" : "body2",
"id" : ObjectId("5e396faeac120790c4561x2t")
}
],
"name" : "jarvis",
"email" : "jarvis@yahoo.com",
"password" : "123",
"__v" : 0
}
【问题讨论】:
-
欢迎,类似的问题之前已经回答过,例如。 link。您还可以在 MongoDB 的 documentation 中找到有关处理嵌套文档的更多信息。
-
您想始终更新
post[]中的first 元素或具有id = ObjectId("5e396faeac120790c4561f4b")的帖子