1

例如,我们在集合测试中有文档。

>> db.test.find()
{ name: abc,  child: [ {name: child1, age:10}, 
                       {name: child2, age:20}, 
                       {name: child3, age:30} ]}

{ name: abcd, child: [ {name: child1, age:10}, 
                       {name: child2, age:20}, 
                       {name: child3, age:30} ]}

我想从第一个文档中的子集中删除年龄等于 10 的那个。我该怎么做?预期的结果应该是:

{ name: abc,  child: [ {name: child2, age:20}, 
                       {name: child3, age:30} ]}

{ name: abcd, child: [ {name: child1, age:10}, 
                       {name: child2, age:20}, 
                       {name: child3, age:30} ]}
4

1 回答 1

1

最简单的方法是使用updatewith $pull;

db.test.update({name:'abc'}, {$pull: {'child': {'age':10}}})

演示;

> db.test.find()
{ "_id" : ObjectId("52034a77a45fcb007cbab9ac"), "name" : "abc", 
      "child" : [{ "name" : "child1", "age" : 10 },     
                 { "name" : "child2", "age" : 20 },
                 { "name" : "child3", "age" : 30 } ] }
{ "_id" : ObjectId("52034a7aa45fcb007cbab9ad"), "name" : "abcd", 
      "child" : [ { "name" : "child1", "age" : 10 },
                  { "name" : "child2", "age" : 20 },
                  { "name" : "child3", "age" : 30 } ] }

> db.test.update({name:'abc'}, {$pull: {'child': {'age':10}}})
> db.test.find()
{ "_id" : ObjectId("52034a77a45fcb007cbab9ac"), "name" : "abc", 
      "child" : [{ "name" : "child2", "age" : 20 },
                 { "name" : "child3", "age" : 30 } ] }
{ "_id" : ObjectId("52034a7aa45fcb007cbab9ad"), "name" : "abcd", 
      "child" : [ { "name" : "child1", "age" : 10 },
                  { "name" : "child2", "age" : 20 },
                  { "name" : "child3", "age" : 30 } ] }

编辑:关于你在评论中的问题,这里是如何对 'abcd' 的 30 岁孩子发表评论;

db.test.update({name:'abcd', 'child.age':30}, 
               {$set: {'child.$.comment': 'nothing'}})
于 2013-08-08T07:34:28.903 回答