引用资料:
对于 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
最佳答案
I wonder if the driver is smart enough to only update the smallest subset of changes or if it's just blindly updating the entire thing?
不,如果您使用“正常”更新方法,整个对象将通过网络发送。 我怀疑数据库服务器本身会足够聪明,只更新必要的索引(而不是那些没有改变的索引),如果可能的话(即对象可以就地更新并且不必移动,因为它也增长了很多)
您可以做的是使用“原子更新修饰符”功能。 Java 文档对它们有点轻描淡写,但由于驱动程序只是传输 JSON,因此非 Java 教程中的内容应该可以工作,例如:
shapes.update((DBObject)JSON.parse( "{ 'foo' : 'bar'}"),
(DBObject) JSON.parse( "{ '$set' : { 'foo': 'bat'}}") );
关于java - 如何使用 java 驱动程序更新 mongo db 中的文档字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3580529/