参考资料:

对mongo db来说仍然很新,但我正在try 更新集合中现有文档的一部分...不幸的是,上面的链接没有更新示例.

基本上,我只想能够:

  1. 向文档中添加新字段
  2. 更新文档的现有字段

以下是我的代码(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

推荐答案

我想知道驱动程序是否足够聪明,只更新最小的更改子集,还是只是盲目地更新整个内容?

不,如果使用"正常"更新方法,整个对象将通过网络发送.

您可以使用"原子更新修改器"函数.Java文档对他们来说有点轻松,但由于驱动程序只是传输JSON,非Java教程中的内容应该可以使用,例如:

shapes.update((DBObject)JSON.parse(    "{ 'foo' : 'bar'}"),  
    (DBObject) JSON.parse(          "{ '$set' : { 'foo': 'bat'}}")   );

Mongodb相关问答推荐

在MongoDB中使用explain()和查询时缺少winningPlan''''

Go mongo-驱动程序测试,FindOne未根据给定的筛选器返回正确结果

MongoDb聚合查询问题

使用mongo'db.Decode(&dto)映射一个嵌套的 struct

Mongoose 聚合和多级组

按数组mongodb中的第一个元素排序

如何在 MongoDB 中对字段进行自定义排序

对 MongoDB 集合中的对象数组进行排序

MongoDB聚合多条件

将MongoDB连接到前端?

无法连接到mongolab主机

用 Redis 查询?

Mongoose Schema vs Mongo Validator

在 Nodejs 中配置最大旧空间大小

MongoDb 数据库与集合

查询 Mongoid/rails 3 中的嵌入对象(Lower than、Min 运算符和排序)

使用 mongodb 在数组中查找子文档

单个语句中的多个 mongo 更新运算符?

show dbs 给出Not Authorized to execute command错误

MongoDB聚合框架的索引优化