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

问题描述

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

I'm trying to build MongoDB Java findAndModify query.

主要目的是我想在插入查询中设置 _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 操作字段 $ 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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:27