How to Query Referenced Objects in Mongodb

How do I query referenced objects in MongoDB?

You can now do it in Mongo 3.2 using $lookup

$lookup takes four arguments

from: Specifies the collection in the same database to perform the join with. The from collection cannot be sharded.

localField: Specifies the field from the documents input to the $lookup stage. $lookup performs an equality match on the localField to the foreignField from the documents of the from collection.

foreignField: Specifies the field from the documents in the from collection.

as: Specifies the name of the new array field to add to the input documents. The new array field contains the matching documents from the from collection.

db.Foo.aggregate(
{$unwind: "$bars"},
{$lookup: {
from:"bar",
localField: "bars",
foreignField: "_id",
as: "bar"

}},
{$match: {
"bar.testprop": true
}}
)

How to query by reference field in MongoDB?

You can use below aggregation with mongodb 3.6 and above

db.country.aggregate([
{ "$match": { "name": "VietNam" } },
{ "$lookup": {
"from": Users.collection.name,
"let": { "countryId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$country", "$$countryId" ] } } },
],
"as": "users",
}},
{ "$unwind": "$users" },
{ "$replaceRoot": { "newRoot": "$users" }}
])

MongoDB query referenced documents

Mongodb provides $lookup operator for joining two collections. Its basically like a join in sql, where you'd do a match between _id in A and activity_creator_id in B.
If you're using mongoose odm you'd directly do a populate in the find query in collection B itself.

How to query to get all documents referenced to another collection based on one field as username

You can use the $lookup aggregation to join collections.

db.profiles.aggregate([
{
$match: {
username: "Jakos"
}
},
{
$lookup: {
from: "posts", //the name of the posts collection, change this if it is different
localField: "_id",
foreignField: "username",
as: "posts"
}
},
{
$project: {
username: 1,
posts: 1,
postsCount: {
$size: "$posts"
},
_id: 0
}
}
])

Playground

For mongoose it should be like this in your app:

const profileWithExperiences = await Student.aggregate([
{ $match: { username: res.username.username } },
{
$unwind: "$experience"
},
{
$lookup: {
from: "posts", //the name of the posts collection, change this if it is different
localField: "_id",
foreignField: "username",
as: "posts"
}
},
{
$project: {
username: 1,
posts: 1,
postsCount: {
$size: "$posts"
},
_id: 0
}
}
]);


Related Topics



Leave a reply



Submit