我的项目中有一个真实案例:
> db.foo.insert({a:'1',
... province: [{id:'1',name:'Yogyakarta',state:[{id:'1',name:'bantul'}]}]
... })
然后我找到()......
> db.foo.find();
> { "_id" : ObjectId("5279ef4c6cfd9d5c0e19bbe0"),
"a" : "1",
"province" : [
{"id" : "1",
"name" : "Yogyakarta",
"state" : [
{"id" : "1","name" : "bantul" }
]
}
]
}
如何删除和更新id ='1'
的状态答案 0 :(得分:0)
删除强>
要删除符合删除条件的文档,请使用remove()
参数调用<query>
方法。
db.foo.remove({'province.state.id': '1'})
示例强>
首先,插入数据Yogyakarta - Bantul
db.foo.insert({a:'1', province: [{id:'1',name:'Yogyakarta',state:[{id:'1',name:'bantul'}]}] })
插入数据Jakarta - Jakarta Selatan
db.foo.insert({a:'1', province: [{id:'2',name:'Jakarta',state:[{id:'2',name:'Jakarta Selatan'}]}] })
现在,您有两个文件
db.foo.find();
结果
[
{ "a" : "1", "_id" : { "$oid" : "527b54c6cc937439340367f9" }, "province" : [ { "name" : "Yogyakarta", "id" : "1", "state" : [ { "name" : "bantul", "id" : "1" } ] } ] },
{ "a" : "1", "_id" : { "$oid" : "527b54d3cc937439340367fa" }, "province" : [ { "name" : "Jakarta", "id" : "2", "state" : [ { "name" : "Jakarta Selatan", "id" : "2" } ] } ] }
]
现在,删除子文档province
包含值为state
的字段1
的文档。
db.foo.remove({'province.state.id': '1'})
检查
db.foo.find();
现在,你有一个文件
[
{ "a" : "1", "_id" : { "$oid" : "527b54d3cc937439340367fa" }, "province" : [ { "name" : "Jakarta", "id" : "2", "state" : [ { "name" : "Jakarta Selatan", "id" : "2" } ] } ] }
]
<强>更新强>
默认情况下,update()
方法会更新单个文档。如果multi选项设置为true
,则该方法将更新与查询条件匹配的所有文档。
db.foo.update({'province.state.id': '2'}, { $set: {'a': '2'} })
检查
db.foo.find();
结果
[
{ "a" : "2", "_id" : { "$oid" : "527b54d3cc937439340367fa" }, "province" : [ { "name" : "Jakarta", "id" : "2", "state" : [ { "name" : "Jakarta Selatan", "id" : "2" } ] } ] }
]