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?
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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.
$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.
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
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With