2012-09-27 32 views
10

我有這樣的數據,蒙戈:更新子陣列的子元素MongoDB中

{ 
    "_id" : ObjectId("505fd43fdbed3dd93f0ae088"), 
    "categoryName" : "Cat 1", 
    "services" : [ 
     { 
      "serviceName" : "Svc 1", 
      "input" : [ 
       { "quantity" : 10, "note" : "quantity = 10" }, 
       { "quantity" : 20, "note" : "quantity = 20" } 
      ] 
     }, 
     { 
      "serviceName" : "Svc 2", 
      "input" : [ 
       { "quantity" : 30, "note" : "quantity = 30" }, 
       { "quantity" : 40, "note" : "quantity = 40" } 
      ] 
     } 
    ] 
} 

現在我想更新數量爲「SVC 1」:

{ "quantity" : 10, "note" : "quantity = 10" } 

像:

{"quantity": 100, "note": "changed to 100"} 

我如何做蒙戈?`

正如我硝酸鉀w,運算符只支持第一個數組,有人建議使用sub sub數組元素的索引,但問題是如何在運行時知道該索引? (我使用的是MongoDB的原生C#驅動程序)

在此先感謝您的幫助!

約翰尼

回答

10

既然你有一個數組中的數組,沒有引用嵌套子陣,除非你知道你要更新的陣列中的位置沒有簡單的方法。

因此,舉例來說,你可以用C#相當於更新「SVC 1」的第一個輸入:

db.services.update(

    // Criteria 
    { 
     '_id' : ObjectId("505fd43fdbed3dd93f0ae088"), 
     'services.serviceName' : 'Svc 1' 
    }, 

    // Updates 
    { 
     $set : { 
      'services.$.input.0.quantity' : 100, 
      'services.$.input.0.note' : 'Quantity updated to 100' 
     } 
    } 
) 

如果你不知道該嵌套input陣列的位置,你將有要獲取匹配的services,請在您的應用程序代碼中迭代input數組,然後在$set更新數組。

或者,你可以修改你的嵌套陣列中使用的嵌入式文件代替,例如:

{ 
    "categoryName" : "Cat 1", 
    "services" : [ 
     { 
      "serviceName" : "Svc 1", 
      "input1" : { "quantity" : 10, "note" : "quantity = 10" }, 
      "input2" : { "quantity" : 20, "note" : "quantity = 20" } 
     }, 
    ] 
} 

然後你可以通過名稱更新,例如input1

db.services.update(

    // Criteria 
    { 
     '_id' : ObjectId("5063e80a275c457549de2362"), 
     'services.serviceName' : 'Svc 1' 
    }, 

    // Updates 
    { 
     $set : { 
      'services.$.input1.quantity' : 100, 
      'services.$.input1.note' : 'Quantity updated to 100' 
     } 
    } 
) 
+0

有子文檔,這非常有用是在MongoDB問題跟蹤器中的相關請求[SERVER-267](https://jira.mongodb.org/browse/SERVER-267)(部分通配符支持)。 – Stennie

+0

感謝您的幫助,Stennie!我目前將輸入和輸出數組分組到另一個集合中作爲解決方法。 – Johnny

5

既然你不」 t知道要更新的值的位置,首先用更新的信息插入新值,然後刪除想要更新的值。

db.services.update(
    { 
    '_id' : ObjectId("505fd43fdbed3dd93f0ae088"), 
    'services.serviceName' : 'Svc 1' 
    }, 
    { 
    { $addToSet: { 'services.$.input' : "new sub-Doc" } 
    } 
) 

,然後取下時插入是成功

db.services.update(
    { 
    '_id' : ObjectId("505fd43fdbed3dd93f0ae088"), 
    'services.serviceName' : 'Svc 1' 
    }, 
    { 
    { $pull: { 'services.$.input' : { "quantity" : 10, "note" : "quantity = 10" } } 
    } 
) 

時指數未聞及文件應在崗位有像「輸入」相同的密鑰Update an element in sub of sub array in mongodb

+3

這很有幫助。現在我切換回MySql。謝謝。 – JSideris