Is it possible for aggregate to $addFields with condition?

Sorry for the vague question. Allow me to elaborate:

I have the following data:

Collection Employee got 3 Documents:

{
    _id: ...,
    index: 1,
    name: "Mike",
    companyIndex: 1
},
{
    _id: ...,
    index: 2,
    name: "John",
    companyIndex: 1
},
{
    _id: ...,
    index: 3,
    name: "Jim",
    companyIndex: 2
}

Collection Company got 2 Documents:

{
   _id: ...,
   index: 1,
   name: "Company A"
},
{
   _id: ...,
   index: 2,
   name: "Company B"
}

Now, I am using the code below to add a field of employees into a company upon querying:

data_Employee = await model_Employee.find({ companyIndex: queryingCompanyIndex }) 
					
data_Company = await model_Company.aggregate([ 
	{ 
		$match: {
			index: queryingCompanyIndex
		} 
	},
	{ 
		$addFields: { 
			"employees": data_Employee
		}
	}
]);

This works for one company, but when I query for 2 companies, employees of both companies show up in both companies. Is there some sort of aggregation manipulation that could do what I want? For each company in the query, it should have all employees that has the companyIndex matching its index.

Thank you.

You can use the aggregation $lookup to match the companies with corresponding employees and get the desired result. This is also referred as “joining” the collection data. The following query runs from mongo shell:

db.company.aggregate([
{
   $lookup:
     {
       from: "employee",
       localField: "index",
       foreignField: "companyIndex",
       as: "employees"
     }
}
])

The output:

{
        "_id" : ObjectId("5f50e903501145bdc9363576"),
        "index" : 1,
        "name" : "Company A",
        "employees" : [
                {
                        "_id" : ObjectId("5f50e8d6501145bdc9363573"),
                        "index" : 1,
                        "name" : "Mike",
                        "companyIndex" : 1
                },
                {
                        "_id" : ObjectId("5f50e8d6501145bdc9363574"),
                        "index" : 2,
                        "name" : "John",
                        "companyIndex" : 1
                }
        ]
}
{
        "_id" : ObjectId("5f50e903501145bdc9363577"),
        "index" : 2,
        "name" : "Company B",
        "employees" : [
                {
                        "_id" : ObjectId("5f50e8d6501145bdc9363575"),
                        "index" : 3,
                        "name" : "Jim",
                        "companyIndex" : 2
                }
        ]
}