2016-04-27 67 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