Search code examples
javamongodbspring-data-mongodb

Rename a field in Mongodb collection using Spring data and Java


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/


Solution

  • @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);
             }