2016-04-27 64 views
1

我有以下文件:嵌套在嵌套在其它阵列的阵列的MongoDB更新对象,而不使用数组索引(嵌套更新)

{ 
    "_id" : ObjectId("5720bdac527623f2889"), 
    "planes" : [ 
     { 
      "name" : "plane1", 
      "wings" : [ 
       { 
        "name" : "rightDown" 
       }, 
       { 
        "name" : "rightUp" 
       } 
      ] 
     }, 
     { 
      "name" : "plane2", 
      "wings" : [ 
       { 
        "name" : "leftUp", 
       }, 
       { 
        "name" : "leftDown", 
       } 
      ] 
     } 
    ] 
} 

我想在嵌套在另一个阵列的阵列,以更新一个对象,而不使用数组索引。 在我的示例中,名为'leftDown'的属性'wing'的'plane2'。可能吗 ?

db.planes.update({ 
    planes: { 
    $elemMatch: { 
     wings: { 
     $elemMatch: { 
      name: 'leftUp' 
     } 
     } 
    } 
    } 
}, 
// It would be wonderful if I the $set would look like this, 
// but the error is: 
// "Too many positional (i.e. '$') elements found in path 'planes.$.wings.$'" 
// 
// It seems that $ holds only the value of the first nested 
// object in the array 
{ 
    $set: { 
    'planes.$.wings.$': { 
     name: 'leftMagic' 
    } 
    } 
}) 

MongoDB的3.2文档说: 的位置$操作者可以不被用于横穿多个阵列的查询,诸如遍历嵌套在其它阵列内的数组查询,因为更换为$占位符是一个单一值

但我仍然在等待那个奇迹.. 有没有其他干净/美丽的方式来做一次拍摄更新?

回答

0

不幸的是,位置运算符只能保存一个值。我不认为你可以用你当前的数据结构以单个镜头执行这个更新。

您可以执行一次查找以获取第一个数组索引,然后使用位置运算符执行第二个查找,但此时您可以遍历该数组并重新保存该文档。

通过对您的集合进行一些重构,您可以将更新下载到单个操作。退房MongooseJS populate