findAndModify 失败并显示错误:"无法同时更新 'field1' 和 'field1' [英] findAndModify fails with error: "Cannot update 'field1' and 'field1' at the same time

查看:30
本文介绍了findAndModify 失败并显示错误:"无法同时更新 'field1' 和 'field1'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建 MongoDB Java findAndModify 查询.

I'm trying to build MongoDB Java findAndModify query.

主要目的是想自己在insert查询中设置_id.

The main purpose is that I would like to set _id in insert query by myself.

这是我的代码:

BasicDBObject findFilter = new BasicDBObject("type", "group")
//
BasicDBObject dialogInsertObject = new BasicDBObject("name", "my group").append("_id", new ObjectId());
//
BasicDBObject dialogUpdateObject = new BasicDBObject("name", "my group");
//
BasicDBObject upsertMap = new BasicDBObject();
upsertMap.append("$setOnInsert", dialogInsertObject);
upsertMap.append("$set", dialogUpdateObject);


DBObject dialogObject = dialogCollection.findAndModify(findFilter, 
   new BasicDBObject("_id", "1"), null, false, upsertMap, true, true);

然后我得到一个错误:

com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , 
  "errmsg" : "exception: Cannot update 'name' and 'name' at the same time" , 
  "code" : 16836 , "ok" : 0.0}

有人可以帮忙吗

推荐答案

这里的基本问题是:

db.collection.update(
   { "type": "group" },
   { 
      "$set": { "mygroup": "value" }
      "$setOnInsert" { "mygroup": "value" }
   }
)

这基本上就是你想要做的.

Which is basically what you are trying to do.

您不能将 $set 操作中的 same 字段作为 $setOnInsert 操作.

You cannot address the same field in a $set operation as a $setOnInsert operation.

导致您遇到错误的逻辑存在普遍问题.

There is a general problem in the logic that causes the error you are experiencing.

这篇关于findAndModify 失败并显示错误:"无法同时更新 'field1' 和 'field1'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆