Reputation: 47
I have collection having below data structure
{
"Shop": "123",
"date": "28-05-2015",
"Points": {
"a": "1",
"b": "2",
"c": "3"
}
}
Here shop and date has unique indexes and no id is there except _id , So if I want to update only b's value and if the record matching(based on account and date ) is not there than should create new record having same structure with b's value. The most important part is its bulk operation means I need to create/update record per day for all the shops and these record will create for every shop per day .So while update a point if record is not there than create it else update the existing record .I am using spring . I tried using update with upsert true but it's not updating rather creating a new record with only updated value .And what is best way to update multiple shop with given updated points .
Upvotes: 0
Views: 4586
Reputation: 2650
//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 );
in case of bulk operation
// 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();
Upvotes: 2