【问题标题】:update nested array object using positional operator使用位置运算符更新嵌套数组对象
【发布时间】:2018-08-03 03:07:53
【问题描述】:

我的文档对象看起来像这样

{ 
   "_id" : ObjectId("5b62cfac2046e98de373399c"),
   "hindi" : {
    "confirmed" : false, 
    "assigned_to" : "xyz+4@abc.com", 
    "candidates" : [

            {
            "candidate_id" : "9262c520-9640-11e8-bfbf-292ac77d55f9", 
            "value" : "स्क्रॉल कैसे करें ?", 
            "createdAt" : NumberInt(1533207154), 
            "createdBy" : "xyz+4@abc.com", 
            "warningList" : [], 
            "comments" : [
                "Correction कैसे स्क्रॉल करें", 
                "added ?"
            ]
           }, 
           {
            "candidate_id" : "297bb060-9642-11e8-ac2d-93ac27f5ee90", 
            "value" : "स्क्रॉल कैसे करें ?", 
            "createdAt" : NumberInt(1533207154), 
            "createdBy" : "xyz+4@abc.com", 
            "warningList" : [], 
            "comments" : [
                "Correction कैसे स्क्रॉल करें", 
                "added ?"
            ]
          }
    ]
}

我的目标是通过candidate_id 找到candidates 数组中的特定项目并更新comment 字段。

这是我正在使用 MongoDB positional operator($) 尝试的查询,但出现错误 Unsupported projection option: $set: { hindi.candidates.$.comments: [] }

db.getCollection("strings").update({_id: ObjectId("5b62cfac2046e98de373399c"),"hindi.candidates.candidate_id": "297bb060-9642-11e8-ac2d-93ac27f5ee90"}, {$set :{"hindi.candidates.$.comments" : []}})

【问题讨论】:

  • 你想在commentsarray 中推送一些东西还是想$set 它作为[]
  • 正确的语法是db.getCollection("strings").update( { "_id": ObjectId("5b62cfac2046e98de373399c"), "hindi.candidates": { "$elemMatch": { "candidate_id": "297bb060-9642-11e8-ac2d-93ac27f5ee90" } } }, { "$set": { "hindi.candidates.$.comments" : [] }} )
  • @AnthonyWinzlet 视需求而定,有时只需设置为空,有时可以包含新值
  • 你对更新查询使用了不正确的语法...试试上面那个
  • @AnthonyWinzlet 现在工作正常。你能详细说明错误是什么吗?

标签: mongodb


【解决方案1】:

这里需要使用$elemMatch来匹配数组内部

db.getCollection("strings").update(
  {
    "_id": ObjectId("5b62cfac2046e98de373399c"),
    "hindi.candidates": { "$elemMatch": { "candidate_id": "297bb060-9642-11e8-ac2d-93ac27f5ee90" } }
  }, 
  { "$set": { "hindi.candidates.$.comments" : [] }}
)

【讨论】:

    猜你喜欢
    • 2013-01-29
    • 2017-01-15
    • 2016-07-12
    • 2021-11-27
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多