Computer >> Computer tutorials >  >> Programming >> MongoDB

Is it possible to rename _id field after MongoDB group aggregation?


Yes, it is possible to rename using aggregation. Let us first create a collection with documents

> db.renameIdDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a1760353decbc2fc927c5")
}
> db.renameIdDemo.insertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a1765353decbc2fc927c6")
}
> db.renameIdDemo.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a176b353decbc2fc927c7")
}

Following is the query to display all documents from a collection with the help of find() method

> db.renameIdDemo.find();

This will produce the following output

{ "_id" : ObjectId("5c9a1760353decbc2fc927c5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c9a1765353decbc2fc927c6"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c9a176b353decbc2fc927c7"), "StudentName" : "David" }

Following is the query to rename _id field:

> db.renameIdDemo.aggregate({ $project: {
...    _id: 0,
...    mainId: "$_id",
...    count: 1,
...    sum: 1
... }
... }
... );

This will produce the following output. We have renamed _id to mainId;

{ "mainId" : ObjectId("5c9a1760353decbc2fc927c5") }
{ "mainId" : ObjectId("5c9a1765353decbc2fc927c6") }
{ "mainId" : ObjectId("5c9a176b353decbc2fc927c7") }