参考资料:
对mongo db来说仍然很新,但我正在try 更新集合中现有文档的一部分...不幸的是,上面的链接没有更新示例.
基本上,我只想能够:
- 向文档中添加新字段
- 更新文档的现有字段
以下是我的代码(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"));
这几乎会撞击整个物体...我可以try 修改原始形状对象,然后对其运行更新.但在那之前,does anyone have experience updating just individual fields (rather than the entire document)?
编辑:
我只是try 了一下,通过使用新的和/或更新的字段发送整个对象,我成功地进行了更新,这很有效.我想知道驱动程序是否足够聪明,只更新最小的更改子集,还是只是盲目地更新整个内容?(在下面的例子中,它只是在更新导线上的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