Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 437
feerlay Avatar asked Mar 01 '18 16:03

feerlay


People also ask

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

What is $lookup in MongoDB?

$lookup performs an equality match on the localField to the foreignField from the documents of the from collection. If an input document does not contain the localField , the $lookup treats the field as having a value of null for matching purposes.


1 Answers

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
    }}
 ])
like image 90
Murugan Perumal Avatar answered Oct 24 '22 01:10

Murugan Perumal