Raman
Raman

Reputation: 215

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/

Upvotes: 1

Views: 3196

Answers (2)

Nick C
Nick C

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:

  1. Tell mongoTemplate we want to run an update(OurClass.class) on the desired class of some MongoDB collection

The hard part:

  1. Select all documents in the MongoDB collection that have a field called "field1" or "field2" or "whatever_you_call_your_class_property". Note that this filter is created inside of the 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:

  1. Apply the rename update by creating an org.springframework.data.mongodb.core.query.Update instance that runs its rename("old_field_name", "new_field_name") as many times as you need
  2. The all() function finally runs the update on any matching documents

Upvotes: 0

Pranay Nailwal
Pranay Nailwal

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

Related Questions