I have the following model in mongo db:
User collection
{
_id:12345,
name:"Joe",
age:15,
}
Addresses collection
{
_id:7663,
userId:12345,
Street:"xyz",
number:"1235",
city:"New York",
state:"NY"
}
Now I want to get all the addresses of users above the age of 20. What I thought was to query all the ids of users above 20 and with the result of this query use the $in operator to find the addresses.
My question is, is there a way to turn this into one query? Is there a better way to query this? (obs: this is just an example, with my problem I cannot embed addresses into users)
Use the aggregation framework where the
$lookup
pipeline stage provides the functionality to join the two collections:The above will create a new array field called
address
(as specified in the$lookup
as option) and this contains the matching documents from the from collection addresses. If the specified name already exists in the input document, the existing field is overwritten.