Reputation: 215
I have a collection with several fields and would like to update both the field name through Java program. For example
{_id : ObjectId(xxxxxxxxxxxx), field1: "value1", field2 : "value2"}
Now I have a requirement to rename the field1 to say field11. How do I do it using Spring Data.
Basically this ops using Java https://docs.mongodb.com/manual/reference/operator/update/rename/
Upvotes: 1
Views: 3196
Reputation: 430
An alternative method that might be a bit easier to understand (thanks in part to the documentation) is the following:
mongoTemplate.update(YourClass.class)
.matching(
new Criteria().orOperator(
where("field1").exists(true), where("field2").exists(true)
)
)
.apply(
new Update()
.rename("field1", "new_field_1").rename("field2", "new_field_2")
).all();
To explain each part:
update(OurClass.class)
on the desired class of some MongoDB collectionThe hard part:
matching()
function using an instance of org.springframework.data.mongodb.core.query.Criteria
that will select any document with a field with a matching name (even if it only matches one field we want to rename). Each where()
call is its own Criteria instance (albeit created by static org.springframework.data.mongodb.core.query.Criteria.where
), which looks for documents with the field name we provide and just checks if the field exists in the document.The fairly straightforward part:
org.springframework.data.mongodb.core.query.Update
instance that runs its rename("old_field_name", "new_field_name")
as many times as you needall()
function finally runs the update on any matching documentsUpvotes: 0
Reputation: 542
@Autowired
MongoTemplate mongoTemplate;
void renameFunction() {
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$rename",new BasicDBObject().append("field1", "field11").append("field2", "field22"));
mongoTemplate.getCollection("Collection_Name").updateMany(searchQuery,updateQuery);
}
Upvotes: 4