How to rename a field name inside array

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'

so I want to rename groupId field name to classid in every document and every lessons element. Firstly I wrote some JS script operation, but then I learned that eval is deprecated and as a result forEach and script operations cannot be used. What is the aggregation I could use in this situation, the complete aggregation is also very welcome, of course.

Thank you for your attention.

Hello @Alikhan_Oitan, Welcome to MongoDB Developer Forum :slight_smile: ,

You can use update with aggregation pipeline starting from MongoDB 4.2,

  • check query update only where groupId is exists
  • $map to iterate loop of lessons and result your required fields
  { "lessons.groupId": { $exists: true } },
    $set: {
      lessons: {
        $map: {
          input: "$lessons",
          in: {
            classid: "$$this.groupId",
            someField: "$$this.someField"
  { multi: true }

Thank you, @turivishal !

I also came up with this kind of solution just now, but I could not use it in java, since scriptOps has been deprecated.

I am using import I am not expecting you to answer this, but in the official documents and google there are no examples on mapping using I am not sure why, maybe this is a new update. Could you please give some example in Java and specifically

I came up with something like this using autocomplete hints, but that’s all. I don’t know how to finish from here.

final Query deletedQuery = Query.query(Criteria.where("deleted").is(true));
Update groupToClassUpdate = new Update().set("lessons", Map.itemsOf("$lessons").as("lesson").andApply());
template.updateMulti(deletedQuery, groupToClassUpdate, Timetable.class);

But using "lessons.groupId": { $exists: true} is sure helpful. I would add that too.

Thank you for your help and reply @turivishal :slight_smile:

I am really sorry, I’m not aware of java syntax, someone will help you with this or you can ask new post with java tag.

1 Like

Thanks! I appreciate your help! Will do! @turivishal

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.