【问题标题】:MongoDB - how to update object using a field in the objectMongoDB - 如何使用对象中的字段更新对象
【发布时间】: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") 的帖子

标签: mongodb mongoose nosql


【解决方案1】:

你是这个意思吗?

yourModel.updateOne({
    "posts.id": ObjectId("5e396faeac120790c4561f4b")
}, {
    $set: {
        "posts.0.title": "new title",
        "posts.0.desc": "new body"
    }
}).then(console.log).catch(console.log);

【讨论】:

  • 你怎么知道你总是要更新元素 0?帖子可以在数组posts[]中的任何位置。
  • @WernfriedDomscheit “例如使用它的 id 更改帖子中的第一个对象”。这不是通用的解决方案,我同意。要更新特定元素,我们需要使用位置运算符 $。
【解决方案2】:

这个应该是arrayFilters

db.col.updateMany(
   {},
   {
      $set: {
         "posts.$[p].title": "new title",
         "posts.$[p].desc": "new body"
      }
   },
   { arrayFilters: [{ "p.id": ObjectId("5e396faeac120790c4561f4b") }] }
)

arrayFilters 已在 MongoDB 3.6 版中引入

【讨论】:

  • 非常感谢你能告诉我好的资源来提高我的mongodb知识
  • @YoussefMaher,打开 stackoverflow.com 并尝试回答其他人的问题。尝试仅根据文档找到解决方案,无需 google。
猜你喜欢
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2014-06-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2019-04-18
相关资源
最近更新 更多