zulekha
zulekha

Reputation: 323

how can we rename _id field returned from groupby query in mongodb

I have two schemas users and lessons. I have to fetch lessons group by each user. Also I am storing reference id of user in lesson schema.

To get the result I have done aggregate query in following format

db.lessons.aggregate([{
  $lookup: {
    from: "users",
    localField: "user",
    foreignField: "_id",
    as: "user"
  }
}, {
  "$project": {
    "user": "$user.email",
    "title": "$title",
    "scheduled_at": "$scheduled_at"
  }
}, {
  $group: {
    _id: "$user",
    num_lessons: {
      $sum: 1
    },
    lessons: {
      $push: {
        title: "$title",
        schedule: "$scheduled_at"
      }
    }
  }
}])

From the above query I am able to get the output as below,

{
    "_id" : [ 
        "[email protected]"
    ],
    "num_lessons" : 1.0,
    "lessons" : [ 
        {
            "title" : "welcome to Mongoose",
            "schedule" : {
                "endTime" : ISODate("2017-06-12T08:30:00.000Z"),
                "startTime" : ISODate("2017-06-10T04:00:00.000Z")
            }
        }
    ]
}


{
    "_id" : [ 
        "[email protected]"
    ],
    "num_lessons" : 1.0,
    "lessons" : [ 
        {
            "title" : "welcome to Angularjs",
            "schedule" : {
                "endTime" : ISODate("2017-05-31T09:30:00.000Z"),
                "startTime" : ISODate("2017-05-21T04:00:00.000Z")
            }
        }
    ]
}

Now I want to rename _id to user. Is it possible to achieve this in aggregation pipeline?

Upvotes: 0

Views: 4018

Answers (1)

dipenparmar12
dipenparmar12

Reputation: 3495

we can do it by $project

db.lessons.aggregate([{
  $lookup: {
    from: "users",
    localField: "user",
    foreignField: "_id",
    as: "user"
  }
}, {
  "$project": {
    "user": "$user.email",
    "title": "$title",
    "scheduled_at": "$scheduled_at"
  }
}, {
  $group: {
    _id: "$user",
    num_lessons: {
      $sum: 1
    },
    lessons: {
      $push: {
        title: "$title",
        schedule: "$scheduled_at"
      }
    }
  }
},
{
  $project: {
    _id: 0,
    user: "$_id",
    num_lessons: '$num_lessons',
    lessons: '$lessons',
  }
}
])

I know, i am posting answer too late, but if anybody come here in future, it may helpful to them.

Upvotes: 5

Related Questions