使用where条件更新mongodb中的子文档

时间:2017-10-11 12:14:58

标签: mongodb mongodb-query aggregation-framework

我有这个系列:

{
"_id": 1,
"text": "Breaking News"
"comments" : [
        {
            "comment_id" : "11", 
            "cust_id" : "1", 
            "comments" : "New comments added", 
            "date" : ISODate("2017-10-10T17:36:26.000+0000")
        }, 
        {
            "comment_id" : "12", 
            "cust_id" : "1", 
            "comments" : "second comments added",
            "date" : ISODate("2017-10-11T17:40:54.000+0000")
        }
    ]
}

我想要从"comments" : "second comments added"

的评论子文档更新"comment_id" : "12"
{
    "_id": 1,
    "text": "Breaking News"
    "comments" : [
            {
                "comment_id" : "11", 
                "cust_id" : "1", 
                "comments" : "New comments added", 
                "date" : ISODate("2017-10-10T17:36:26.000+0000")
            }, 
            {
                "comment_id" : "12", 
                "cust_id" : "1", 
                "comments" : "second comments updated by ABC",
                "date" : ISODate("2017-10-11T17:40:54.000+0000")
            }
        ]
    }

我使用下面的查询来更新它,但它每次都会更新第一条评论。

db.demo.update( {"_id" : '1','comments.comment_id' : '12','comments.cust_id': '1'},
{'$set' : {"comments.$.comments" : "second comments updated by ABC"}})

当我使用上述查询时,它会更新每次"comment_id" : "11"的第一条评论。 如果我使用下面的查询它工作正常,

db.demo.update( {"_id" : '1','comments.comment_id' : '12'},
    {'$set' : {"comments.$.comments" : "second comments updated by ABC"}})

但我也需要cust_id在哪里。

如果我做错了,请纠正我。

0 个答案:

没有答案