【问题标题】:MongoDB - update embedded document AND the document itselfMongoDB - 更新嵌入文档和文档本身
【发布时间】:2016-07-18 10:23:11
【问题描述】:

是否可以在一个查询中同时更新文档和该文档中嵌入的数组元素?

例如

Team:
{
   MembersCount: 1,
   Members: [
      {
         Id: 1,
         Role: 1
       }]
 }

示例查询必须为increment MemberCountpush an element to Members arraychange the first member's role

我的研究表明,您可以更新文档或更新数组的元素,但不能同时更新,因为查询必须指向文档或特定元素,但也许我遗漏了一些东西。

编辑: 现在我知道不可能将元素添加到 Scores 数组并修改同一数组中的其他元素(该元素的索引会改变 - 这是我的解释)。

【问题讨论】:

  • 根据我的个人经验,我可以说我们不能同时更新数组及其对象属性。所以我们必须对上述结果使用两个查询。

标签: mongodb mongodb-query


【解决方案1】:

正如您所发现的,您不能在更新数组元素的同时添加到数组中。在 MongoDB v3.2 中,您应该会看到一条错误消息:

Cannot update 'Members.0.Role' and 'Members' at the same time

另一种方法是使用cursor.forEach()。 例如:

/* Find a document using _id */
db.collection.find({
                     "_id":ObjectId("578cda18006d485d118c3b79")
                  })
                  .forEach(function(doc){
                                 /* Increment MemberCount */
                                 doc['MemberCount']+=1; 
                                 /* Push an element to Members array */
                                 doc["Members"].push({"Id":2, "Role":9});
                                 /* Change the first member's role */
                                 doc["Members"][0]["Role"] = 3;
                                 /* Save*/
                                 db.collection.save(doc)
                                })

尽管您需要重新考虑这是否是最适合您的应用程序用例的data model

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 2013-09-18
    • 2019-09-19
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多