2012-09-27 78 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