Home > Software engineering >  How to change name of a field in MongoDB with java for each document in the collection?
How to change name of a field in MongoDB with java for each document in the collection?

Time:10-31

Due to some decisions I will have to change the name of some fields in all documents in a single collection. For purpose of automation testing I am inserting documents and then checking some logics. Lets assume that after the insert method I have the following objects:

    "_id" : ObjectId("60c10042d"),
    "Name" : Mike,
    "years" : 25,
    "Country" : England
},
{
    "_id" : ObjectId("40r10042t"),
    "Name" : Smith,
    "years" : 32,
    "Country" : England
}

When inserting the document/documents I want to change the field "Country" to "Occupation" using Java. Here is example of the code I'm using:

MongoCollection<Document> documentMongo = MongoDb.getCollection("collectionName");
Document document = Document.parse(readJsonFile(json));

//I've tried this way:
//documentMongo.updateMany(document, Updates.rename("Country", "Occupation"));
//didn't work

documentMongo.insertOne(document);

CodePudding user response:

Oh, the rename should be after the insert is done.

documentMongo.insertOne(document);
documentMongo.updateMany(document, Updates.rename("Country", "Occupation"));

Anyway, it could help others which are searching for easy way to change field names.

Sadly, when I try rename more fields it works only for the first one. Final solution:

documentMongoCollection.insertOne(document);
            BasicDBObject searchQuery = new BasicDBObject();
            BasicDBObject updateQuery = new BasicDBObject();
            updateQuery.append("$rename",new BasicDBObject().append("oldField", "newField").append("oldField1", "newField1").append("oldField2", "newField2"));
            documentMongoCollection.updateMany(searchQuery,updateQuery);
  • Related