Search code examples
databasemongodblookup

How to lookup only for specific fields in mongo


How to join only specific fields? When using $lookup, mongo returns the whole document.

Let's say that's my data:

users

[
    { id: 0, name: "Bob", adj: 1 },
    { id: 1, name: "Will", adj: 2 },
]

adjectives

[
    { id: 1, name: "awesome" },
    { id: 2, name: "cool" },
]

I want to do a lookup, so the response should be like:

[
    { id: 0, name: "Bob", adj: 1, adj_value: "awesome" },
    { id: 1, name: "Will", adj: 2, adj_value: "cool" },
]

This is my try

db.collection('users').aggregate([
    {
        $lookup: {
            from: 'adjectives',
            localField: 'adj',
            foreignField: 'name',
            as: 'adjective_value'
         },
     },
 ])

But it inserts whole document into a user document. How to get only single field in response?


Solution

  • In $project pipe you can get single field from lookup collection object.

    db.collection('users').aggregate([
        {
            $lookup: {
                from: 'adjectives',
                localField: 'adj',
                foreignField: 'id',
                as: 'adjective_value'
             },
         },
        {$unwind:'$adjective_value'},
        {$project:{
             adjective_value:'$adjective_value.name',
             id: 1, 
             name: 1, 
             adj: 1
        }}
     ])