参考文献:
仍然是mongo db的新手,但我正在尝试更新集合中现有文档的一部分......遗憾的是,上面的链接没有更新示例.
基本上,我只是希望能够:
这是我的代码(Grails + Groovy + Java + MongoDB + java驱动程序):
def shape = mongo.shapes.findOne(new BasicDBObject("data", "http://www.foo.com")); // get the document
mongo.shapes.update(new BasicDBObject("_id", shape._id), new BasicDBObject("isProcessed", 0)); // add a new "isProcessed" field set to 0
mongo.shapes.update(new BasicDBObject("_id", shape._id), new BasicDBObject("data", "http://www.bar.com"));
Run Code Online (Sandbox Code Playgroud)
这几乎破坏了整个对象...我可能只是尝试修改原始形状对象,然后在其上运行更新.但在那之前,是否有人有更新单个字段(而不是整个文档)的经验?
编辑:
我只是尝试了它,并且能够通过发送整个对象以及新的和/或更新的字段来成功更新.我想知道驱动程序是否足够聪明,只更新最小的更改子集,或者只是盲目更新整个事物?(在下面的例子中,它只是更新电线或整个形状文档的foo字段?)
码:
def shape = mongo.shapes.findOne(); // get the first shape to use as a base
shape.removeField("_id"); // remove the id field
shape.put("foo","bar"); // add a new field "foo"
mongo.shapes.insert(shape); …Run Code Online (Sandbox Code Playgroud)