0

我的项目中有一个真实案例:

> 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' 的状态

4

1 回答 1

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其 value的字段的文档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"   } ]   } ]   }
]
于 2013-11-07T09:06:22.060 回答