例如,我们在集合测试中有文档。
>> 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} ]}
答案 0 :(得分:1)
最简单的方法是将update
与$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'}})