Rahul Anand
Rahul Anand

Reputation: 573

Mongodb Lookup query on collections with ObjectId as local and foreign fields?

I have two collections on which i have to do lookup query on ObjectId of both collections. Both local and foreign fields are of type ObjectId. I can convert one collection ObjectId to string with $toString method but how will i do the same with the other collection i want to join?

Json 1:

{
    "_id": {
        "$oid": "4efcggedwrg446"
    },
    "name": "Name1",
    "phone": "12345678"
}

Json 2:

{
  "_id": {
    "$oid": "4efcggedwrg446"
  },
  "deviceId": "6552gggh732",
  "deviceName": "samsung"
}

Query:

[{$addFields: {
  "Id": { "$toString": "$_id" }
}}, {$lookup: {
  from: 'json2',
  localField: 'Id',
  foreignField: '_id',
  as: 'join'
}}]

Lookup query on _id of both json. How can i convert ObjectId of other collection ?

Upvotes: 0

Views: 1088

Answers (1)

Nikhil Savaliya
Nikhil Savaliya

Reputation: 2166

Collection1

{
    "_id" : ObjectId("5e33bfc008591b180967753a"),
    "name" : "Name1",
    "phone" : "12345678"
}

Collection2

{
    "_id" : ObjectId("5e33bfe508591b180967753b"),
    "iUserId" : ObjectId("5e33bfc008591b180967753a"),
    "deviceId" : "6552gggh732",
    "deviceName" : "samsung"
},

To join both with lookup

const query = [
    {
        $lookup:
            {
                from: "Collection2",
                localField: "_id",
                foreignField: "iUserId",
                as: "User"
            }
    },
    {
        $unwind: "$User"
    }
];

db.Collection1.aggregate(query)

Result:- You can apply $project to get specific fields

{
    "_id" : ObjectId("5e33bfc008591b180967753a"),
    "name" : "Name1",
    "phone" : "12345678",
    "User" : {
        "_id" : ObjectId("5e33bfe508591b180967753b"),
        "iUserId" : ObjectId("5e33bfc008591b180967753a"),
        "deviceId" : "6552gggh732",
        "deviceName" : "samsung"
    }
}

Upvotes: 0

Related Questions