How to rename the fields using FindIterable.map() function programmatically using Java?

How to rename the fields using FindIterable.map() function programmatically using Java?

MongoDoc:

{
"first_name" : "Terry",
"last_name" : "James"
}

Expected Format:

{
"fname" : "Terry",
"lname" : "James"
}

Sample Code:

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static com.mongodb.client.MongoClients.create;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class MyFind {

	public static void main(String[] args) {
		String connectionString = "< Enter the connection string >";
		String database = "< Enter the database >";
		String collectionName = "< Enter the collectionName >";
		new MyFind().executeMongoFind(connectionString, database, collectionName);

	}

	private void executeMongoFind(String connectionString, String database, String collectionName) {
		MongoClientSettings settings = getMongoClientSettings(connectionString);
		MongoClient client = create(settings);
		MongoDatabase mongoDatabase = null;
		try {
			mongoDatabase = client.getDatabase(database);
			Bson filterCriteria = getFilter();
			Bson projectionFields = getProjectionFields();
			FindIterable iterable = mongoDatabase.getCollection(collectionName).find(filterCriteria);
			iterable = iterable.projection(projectionFields);

		/*
			db.collection_name.find({},{'first_name': 1, _id:0})
			.map( doc => ({ firstName: doc['first_name']}));
		*/
			/* iterable.map(Function fn) */

			MongoCursor<Document> mongoCursor = iterable != null ? iterable.iterator() : null;
			while (mongoCursor.hasNext()) {
				Document doc = mongoCursor.next();
				System.out.println(doc.toJson());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private MongoClientSettings getMongoClientSettings(String connectionString) {
		ConnectionString connection = new ConnectionString(connectionString);
		CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
				fromProviders(PojoCodecProvider.builder().automatic(true).build()));
		MongoClientSettings settings = MongoClientSettings.builder()
				.applyConnectionString(connection)
				.codecRegistry(codecRegistry)
				.build();
		return settings;
	}

	private Bson getProjectionFields() {

		Set<String> projectionFieldSet = new ConcurrentHashMap<>().newKeySet();
		projectionFieldSet.add("first_name");
		projectionFieldSet.add("last_name");
		Bson projectionFields = Projections
				.fields(Projections.include(projectionFieldSet
						.stream().toArray(String[]::new)), Projections.excludeId());
		return projectionFields;
	}

	private Bson getFilter() {

		Bson filterCriteria = Filters.and(Filters.eq("first_name", "Terry"));
		return filterCriteria;
	}

}

FYI,
I’ve tried using aggregate, but it is taking more time than I expected. So to try out some alternate approaches, I raised this ticket.

Reference : How do I rename fields when performing search/projection in MongoDB? - Stack Overflow

Hi @Vignesh_Paulraj and welcome to MongoDB community forums!!

From the Stack Overflow link posted above, I see that your query has been responded.
However, if you are still looking to rename the field name in MongoDB, you can make use of the $rename operator, which could be used to rename the filed names.
As mentioned in the documentation, $rename, under the hood makes use of $set and $unset aggregation operators to modify the filed names.

You can try the below code snippet to make the modification:

var changename = collection.updateMany(eq("i", 1), rename("i", "NAME"), new UpdateOptions().upsert(true));
        System.out.println(changename.getModifiedCount() + " documents updated");

Please don’t hesitate to reach out in case you have further questions.

Warm Regards
Aasawari