【发布时间】:2011-04-04 13:51:46
【问题描述】:
参考资料:
对于 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"));
这几乎破坏了整个对象...我可能会尝试仅修改原始形状对象,然后对其运行更新。但在那之前,有没有人只更新个别字段(而不是整个文档)?
编辑:
我刚刚尝试过,并且能够通过发送带有新和/或更新字段的整个对象来成功更新,这很有效。我想知道驱动程序是否足够聪明,只能更新最小的更改子集,还是只是盲目地更新整个内容? (在下面的例子中,它只是通过网络更新 foo 字段还是整个 shape 文档?)
代码:
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); // insert the new shape
def shape2 = mongo.shapes.findOne(new BasicDBObject("foo", "bar")); // get the newly inserted shape (and more importantly, it's id)
shape2.put("foo", "bat"); // update the "foo" field to a new value
mongo.shapes.update(new BasicDBObject("_id", shape2._id), shape2); // update the existing document in mongo
【问题讨论】:
标签: java mongodb grails groovy mongo-java