问题
I am searching for the right way to implement the upsert operation to a Mongo Collection using the API given by Spring Data.
In details, I have the following use case. The schema of the collection collection is something like the following:
{
_id: "some_id",
field1: "value1",
field2: "value2",
subdocument1: {
// A subdocument with some fields
},
subdocument2: {
// A subdocument with some other fields
}
}
The fields field1 and field2 are always present, but subdocument1 and subdocument2 will be inserted in different moments: one during the first insertion, the second with a subsequent update.
I saw that MongoTemplate has and upsert method. Using this method I have to build my own the update operation.
Query query = Query.query(Criteria.where("_id").is("some_id"));
Update.update("_id", "some_id")
.set("field1", "value1")
.set("field2", "value2")
.set("subdocument1", subdocumentObject);
mongoTemplate.upsert(query, update, Collection.class);
I cannot understand if it is what I am searching for and if there is a better approach.
回答1:
I believe what you are looking for is $setOnInsert for subdocument1. So something like should work for you.
Query query = Query.query(Criteria.where("_id").is("some_id"));
Update update = Update.update("_id", "some_id")
.set("field1", "value1")
.set("field2", "value2")
.set("subdocument2", subdocumentObject2)
.setOnInsert("subdocument1", subdocumentObject1);
More here https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/
来源:https://stackoverflow.com/questions/43248469/spring-data-mongo-upsert-with-various-fields-updated