无法使用带有upsert的updateone批量更新mongo

时间:2016-12-25 18:55:53

标签: mongodb spring-mongo

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

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工作正常,但如果有任何原因,它将重新创建索引。

1 个答案:

答案 0 :(得分:1)

您不需要此处的批量写入操作。你可以使用常规更新,你应该没事。

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

{{1}}