How to fetch a mongo document with renamed fields without changing the actual data programmatically using Java?
Does Mongo supports this? If so, which one to you use for the data fetch Query or Aggregation?
Ex.
Mongo Doc:
{
"fname": "xyz"
}
Expected Format:
{
"FIRST_NAME" : "xyz"
}
Hey @Vignesh_Paulraj ,
Welcome to the MongoDB Community!
I think you can use the $project stage to get the expected output on your application side. Here is an example code snippet for the same:
private static void reshapeDocs(MongoCollection<Document> coll) {
Bson includeFname = include("fname");
// Compute a new 'FIRST_NAME' field by copying 'fname'
Bson computedFirstName = computed("FIRST_NAME", "$fname");
Bson projection = project(computedFirstName);
MongoCursor<Document> cursor = coll.aggregate(Arrays.asList(projection)).iterator();
Document reshapedDoc = cursor.next();
}
Hope it answers your questions!
Regards,
Kushagra
1 Like
Great help, thanks @Kushagra_Kesav , it works perfect.
One more quick clarification, the output has the actual fields as well.
How can I get them ignored?
Data:
{
"fname": "xyz",
"lname": "qaz",
"address": {
"addressLine": "",
"city": "",
"postCode": "",
"country": ""
}
}
current-code:
public static void reshapeDocs(MongoCollection<Document> mongoColl) {
Bson projectionFields = Aggregates.project(Projections.fields(Projections.excludeId(), Projections.include("fname", "lname"),
Projections.computed("FIRST_NAME", "$fname"), Projections.computed("LAST_NAME", "$lname")));
mongoColl.aggregate(Arrays.asList(projectionFields,
Aggregates.match(Filters.eq("fname", "xyz")))).forEach(doc -> {
System.out.println(doc.toJson());
});
}
Current Result:
{
"fname": "xyz",
"lname": "qaz",
"FIRST_NAME": "xyz",
"LAST_NAME": "qaz"
}
Expected Result:
{
"FIRST_NAME": "xyz",
"LAST_NAME": "qaz"
}
@Kushagra_Kesav Please ignore the last question. Thanks for the guidance on the code.
Found the way to ignore the actual fields. Added another projection stage as below.
Link: How to exclude $project computed field in mongoDB - Stack Overflow
Current Code:
public static void reshapeDocs(MongoCollection<Document> mongoColl) {
Bson projectionFields = Aggregates.project(Projections.fields(Projections.excludeId(), Projections.include("fname", "lname"),
Projections.computed("F_NAME", "$fname"), Projections.computed("L_NAME", "$lname")));
mongoColl.aggregate(Arrays.asList(
projectionFields,
Aggregates.match(Filters.eq("fname", "xyz")),
// Added another projection here to ignore the actual fields.
Aggregates.project(Projections.fields(Projections.exclude("fname", "lname")))
)
).forEach(doc -> {
System.out.println("---------Output------------");
System.out.println(doc.toJson());
System.out.println("---------------------");
});
}
Output:
{
"F_NAME": "xyz",
"L_NAME": "qaz"
}
1 Like
system
(system)
Closed
October 2, 2023, 1:32pm
5
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.