I wanted to rename field inside an array which looks like this:
{
lessons: [
{
someField: someValue,
groupId: 'some id string'
},
{
someField: anotherValue,
groupId: 'another id string'
},
]
}
Unfortunately there are no examples of org.springframework.data.mongodb.core.aggregation.VariableOperators.Map I could find as in the topic How to rename a field name inside array - #2 by turivishal
Hello @Alikhan_Oitan , you can use this update query. This uses the Spring Data MongoDB MongoTemplate:
List<Document> pipeline = Arrays.asList(new Document("$set",
new Document("lessons",
new Document("$map",
new Document("input", "$lessons")
.append("as", "e")
.append("in",
new Document("someField", "$$e.someField")
.append("classId", "$$e.groupId")
)
)
)
));
Document filter = new Document();
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testDB");
UpdateResult result = mongoOps.getCollection("testColl")
.updateMany(filter, pipeline);
System.out.println("Modified count: " + result.getModifiedCount());
2 Likes
Thank you @Prasad_Saya . I applied your solution and it works perfectly! Never realized that we could represent aggregation objects using Document, that simplifies everything!
1 Like
system
(system)
Closed
July 18, 2021, 1:57am
4
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.