user11509999
user11509999

Reputation:

MongoDB Aggregation : Rename a field in mongodb from ObjectId to literal/String?

I have a mongo collection which have fields id,mobile and name array. Below is example of my collection,

        {
        "_id": 1,
        "mobile": "555-555-5555",
        "name": { "first" : ObjectId("1122334455") }
        }

        {
        "_id": 2,
        "mobile": "222-222-2222",
        "name": { "first" : ObjectId("5544332211") }
        }

        {
        "_id": 3,
        "mobile": "111-111-1111",
        "name": { "first" : ObjectId("1122334455")}
        }

I want to rename the first field in array name from ObjectId to literal So my output will be something like this,

       {
        "_id": 1,
        "mobile": "555-555-5555",
        "name": { "first" : "Tom" }
        }

        {
        "_id": 2,
        "mobile": "222-222-2222",
        "name": { "first" : "abigail" }
        }

        {
        "_id": 3,
        "mobile": "111-111-1111",
        "name": { "first" : "Tom"}
        }

Upvotes: 1

Views: 186

Answers (1)

Serkan Arslan
Serkan Arslan

Reputation: 13403

You can use $lookup. I assume that you have user_source collection that keeps your user details.

db.getCollection('Test01').aggregate(
[
    {
       $lookup:
       {
         from: "user_source",
         localField: "name.first",
         foreignField: "_id",
         as: "fromUsers"
       }
    },
    { $addFields : { "name.first":  {$arrayElemAt: [ "$fromUsers.name", 0 ]} } },
    { $project: { fromUsers: 0 } },
]
)

Upvotes: 1

Related Questions