0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you are right, and I was wonder why my query always got empty on companies, because that companies not in the database or deleted LOL, oh ye one more, what is the condition for people company, like say I want to aggregate companies in that people that company created at last month ??
See this document. It describes how to handle conditions and multiple joins. docs.mongodb.com/manual/reference/operator/aggregation/lookup/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.