无法使用 updateone 和 upsert 批量更新 mongo

Not able to update mongo in bulk using updateone with upsert

我遇到了问题。如果已经存在,我正在尝试更新,如果不存在,则插入。我正在使用 API 的 spring-mongo 驱动程序。

DBCollection dbCollection = mongoTemplate.getCollection("supcInfo");
        BulkWriteOperation bulkWriteOperation = dbCollection.initializeUnorderedBulkOperation();
BulkUpdateRequestBuilder builder = bulkWriteOperation.find(new BasicDBObject("_id", supcInfo.getSupc())).upsert();
BasicDBObject dbObject = new BasicDBObject("$set",new BasicDBObject("_id", supcInfo.getSupc()));
         dbObject = dbObject.append("$set",new BasicDBObject("pogId", supcInfo.getPogId()));
         dbObject = dbObject.append("$set",new BasicDBObject("mrp", supcInfo.getMrp()));
         dbObject = dbObject.append("$set",new BasicDBObject("price", supcInfo.getPrice()));
         dbObject = dbObject.append("$set",new BasicDBObject("primarySellerCode", supcInfo.getPrimarySellerCode()));
         dbObject =  dbObject.append("$set",new BasicDBObject("camsEnabled", supcInfo.isCamsEnabled()));
         dbObject =  dbObject.append("$set",new BasicDBObject("availability", supcInfo.getAvailability()));
         dbObject = dbObject.append("$set",new BasicDBObject("updateTs", supcInfo.getUpdateTs()));
builder.updateOne(dbObject);
bulkWriteOperation.execute();

但是所有字段都没有更新。谁能告诉我原因,replaceOne 工作正常,但如果有索引,它会重新创建索引。

这里不需要批量写入操作。您可以使用常规更新,应该没问题。

您对 DBObject 的使用不正确。您正在覆盖 $set 键。

BasicDBObject updateFields = new BasicDBObject("pogId", supcInfo.getPogId()).append("mrp", supcInfo.getMrp()); // Rest of fields.
BasicDBObject dbObject = new BasicDBObject("$set",updateFields);