【问题标题】:MongoDB: Updating subdocumentMongoDB:更新子文档
【发布时间】:2011-08-04 13:04:38
【问题描述】:

我有这个收藏:

[{ "_id" : 7,
   "category" : "Festival",
   "comments" : [
        {
                "_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
                "usr" : "Mila",
                "txt" : "This is a comment",
                "date" : "4/12/11"
        }
    ]
}]

我想要的只是像这样在 cmets 中插入一个新字段:

[{ "_id" : 7,
   "category" : "Festival",
   "comments" : [
        {
                "_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
                "usr" : "Mila",
                "txt" : "This is a comment",
                "date" : "4/12/11",
                "type": "abc"  // find the parent doc with id=7 & insert this inside comments
        }
    ]
}]

如何在 cmets 子文档中插入?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    你需要使用the $ positional operator

    例如:

    update({ 
           _id: 7, 
           "comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
       },{
           $set: {"comments.$.type": abc}
       }, false, true
    );
    

    我没有测试它,但我希望它对你有帮助。

    如果你想改变你需要使用的文档结构

    db.collection.update( 标准, objNew, upsert, multi)

    参数:

    criteria - query which selects the record to update;
    objNew - updated object or $ operators (e.g., $inc) which manipulate the object
    upsert - if this should be an "upsert"; that is, if the record does not exist, nsert it
    multi - if all documents matching criteria should be updated
    

    并插入具有新结构的新 objNew。 check this for more details

    【讨论】:

    • 这对我不起作用。它只是更新数组中的一项,而不是全部。即使我多次通过 true
    • 对我也不起作用。如果我设置 new_cmets.type 它可以工作,但是当我尝试修改现有的父级(如 cmets)时它不起作用
    • 请注意,由于 MongoDB 2.2 版的更新语法是 db.collection.update( , , { upsert: , multi: } )
    • 文档似乎发生了变化。这超出了位置:docs.mongodb.com/manual/reference/operator/update/positional
    【解决方案2】:

    $ 位置运算符只有在 'cmets' 字段不是数组时才能按预期工作。 OP 的 json 格式错误,但它看起来可能是一个数组。

    问题是 mongodb 现在只会更新与查询匹配的数组的第一个元素。虽然有一个 RFE 开放以添加对更新所有匹配数组元素的支持:https://jira.mongodb.org/browse/SERVER-1243

    要解决数组的这个问题,您只需定期查找,然后单独更新数组中的元素。

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      相关资源
      最近更新 更多