Reputation: 243
I have a person like this, The person has many companies, [ ONE TO MANY ]
{
"_id" : ObjectId("5eef12533167638883fba5ad"),
"companies" : [
ObjectId("00000000000000000011111") ,
ObjectId("0000000000000000022222")
],
"email" : "[email protected]",
"phoneNumber" : "+1689999999999",
"createdAt" : ISODate("2020-06-21T07:54:56.529Z"),
"updatedAt" : ISODate("2020-06-21T07:54:56.529Z")
}
I want to aggregate companies into the company data I am trying like this
db.people.aggregate(
{ "$lookup": {
"from": "companies",
"localField": "companies",
"foreignField": "_id",
"as": "companies"
}},
)
but the result is the same as query db.people.find() how to correct way to query that she in that array show the companies data ,
what I expected is :
{
"_id" : ObjectId("5eef12533167638883fba5ad"),
"companies" : [
{
"_id": ObjectId("00000000000000000011111"),
"name": "Company one"
},
..... so on
],
"email" : "[email protected]",
"phoneNumber" : "+1689999999999",
"createdAt" : ISODate("2020-06-21T07:54:56.529Z"),
"updatedAt" : ISODate("2020-06-21T07:54:56.529Z")
}
Upvotes: 0
Views: 187
Reputation: 2679
IMPORTANT: Starting MongoDB 3.4, if the localField
is an array, you can match the array elements against a scalar foreignField
without needing an $unwind stage.
I believe your aggregate call is not right. .aggregate()
receives an array.
db.people.aggregate([
{
$lookup: {
from: "companies",
localField: "companies",
foreignField: "_id",
as: "companies"
}
}
])
Make sure the from
, localField
and foreignField
are correct.
Upvotes: 1