【问题标题】:Adding a property to array items results in "The positional operator did not find the match needed from the query"向数组项添加属性会导致“位置运算符未找到查询所需的匹配项”
【发布时间】:2018-12-14 11:31:35
【问题描述】:

我正在尝试将属性添加到嵌套数组中

var names = [...]; // long list of names, omitted for the sake of brevity

var isNotCriteria = {
    "Persons.Name": {
        $nin: names
    }
}

var isNotUpdateStatement = {
    $set: {
        "Persons.$.IsVerified" : false
    }
}

db["teams"].updateMany(isNotCriteria, isNotUpdateStatement);

teams 文档结构示例:

{
   "_id": "32bace05-2742-4bee-9d56-6e4f168e742b",
   "Name" : "TeamA",
   "Persons" : [{
       "_id" : "5794aa39-8ebf-421d-a28b-ab34d1ccfb2h",
       "Name" : "Person 1"
   }, {
       "_id" : "42602118-cc4a-4121-b869-365d6f73e1d0",
       "Name" : "Person 2"
   }]
}

但是,执行会导致异常:

位置运算符未从查询中找到所需的匹配项。 未扩展更新:Persons.$.IsVerified

我无法理解失败的原因,因为如果我将条件查询从 $nin 切换到 $in 它可以工作。 如果我使用此标准运行find,我确实会看到结果:

db["teams"].find(isNotCriteria);

知道如何解决这个问题吗?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    问题原来是teams 文档没有Persons 数组(或数组为空)。 我将条件查询更改为

    var isNotCriteria = {
        $and: [
             {
                 "Persons": {
                     $exists: true,
                     $not: {$size : 0} 
                 },
                 "Persons.Name" : {
                      $nin: names
                 }
             }
         ]
     }
    

    现在它按预期工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多