feerlay
feerlay

Reputation: 2638

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?

Upvotes: 13

Views: 10997

Answers (2)

user19782013
user19782013

Reputation: 1

  {
    $lookup: {
      from: "products",
      localField: "productid",
      foreignField: "_id",
      as: "products"
    },
  },
  {
    $lookup: {
      from: "teches",
      localField: "techesname",
      foreignField: "_id",
      as: "teches"
    },
  },
  {
    $project:
    {
      products: '$products.name',
      teches: '$teches.name',
      productid: 1,
      techesname: 1,
    }
  }

Upvotes: 0

Murugan Perumal
Murugan Perumal

Reputation: 985

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
    }}
 ])

Upvotes: 23

Related Questions