【问题标题】:Update or create if not exist Mongo 3.0.4如果不存在,则更新或创建 Mongo 3.0.4
【发布时间】:2017-05-01 08:01:15
【问题描述】:

我的集合具有以下数据结构

{ "Shop": "123", "date": "28-05-2015", "Points": { "a": "1", "b": "2", "c": "3" } }

这里的 shop 和 date 有唯一的索引,除了 _id 之外没有 id , 因此,如果我只想更新 b 的值并且如果记录匹配(基于 account 和 date )不存在,那么应该创建与 b 的值具有相同结构的新记录。 最重要的部分是它的批量操作意味着我需要每天为所有商店创建/更新记录,这些记录将每天为每个商店创建。因此,如果记录不存在则更新一个点而不是创建它,否则更新现有的记录。我正在使用弹簧。 我尝试使用带有 upsert true 的更新,但它并没有更新,而是创建一个只有更新值的新记录。以及用给定的更新点更新多个商店的最佳方法是什么。

【问题讨论】:

  • 你能把upsert代码贴在这里吗?
  • 我是在 Mongo shell 本身上做的。使用带有不高兴标志的更新查询作为真......在mongo 3.4中,更新中有$set标志正在工作,但它不在3.0中。意思是我会在几个小时内更新代码。
  • 我将添加一些示例代码,您可以根据您的代码对其进行验证。

标签: spring mongodb spring-data upsert


【解决方案1】:
//search a document that doesn't exist
Query query = new Query();
query.addCriteria(Criteria.where("points.b").is("some value"));

Update update = new Update();
update.set("b", some value);
update.set..... //set all needed fields else they go as null

mongoOperation.upsert(query, update, Shop.class);

Shop shopTestObj = mongoOperation.findOne(query, Shop.class);
System.out.println("shopTestObj - " + shopTestObj );

批量操作

// Sample code
com.mongodb.DBCollection collection = db.getCollection("shop");

// Get  BulkWriteOperation by accessing the mongodb com.mongodb.DBCollection class on mycol //Collection

BulkWriteOperation  bulkWriteOperation= collection.initializeUnorderedBulkOperation();

//perform the upsert  operation in the loop to add objects for bulk execution 
for (int i=0;i<100;i++)
{
// get a bulkWriteRequestBuilder by issuing find on the shop with _id
BulkWriteRequestBuilder bulkWriteRequestBuilder=bulkWriteOperation.find(new BasicDBObject('_id',Integer.valueOf(i)));

// get hold of upsert operation from bulkWriteRequestBuilder
BulkUpdateRequestBuilder updateReq=              bulkWriteRequestBuilder?.upsert()

updateReq. replaceOne (new BasicDBObject("_id",Integer.valueOf(i)).append("points.b", "some value"));

}
// execute bulk operation on shop collection
BulkWriteResult result=bulkWriteOperation.execute();

【讨论】:

  • BulkWriteRequestBuilder 是基于 _id 还是 upsert 是基于 _id 有什么理由吗?
  • 这只是一个示例。
  • 我得到了没有批量更新的上半部分。你能解释一下批量更新部分吗?如果我有一个对象列表,可以说商店和日期是唯一的,所以我只想更新 a,b,而不是如何这将起作用,而且您正在使用 BasicDBObject ,我如何使用我的对象而不是那个
  • 上述简单的 upsert 没有正确的行为,当我只想更新一个字段时,它的创建记录只有该字段并用它创建新记录。
猜你喜欢
  • 2023-02-06
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2012-10-12
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
相关资源
最近更新 更多