Hey everyone, I wonder what is the best way to create relations between two documents in 2 different collections using “db.collection.updateMany”?
Let’s say I have one Companies collection:
[
{ _id: 1, name: “tesla”, location: “somewhere”},
{ _id: 2, name: “google”,location: “somewhereElse” },
]
And one Employees collection:
[
{ _id: 154, name: “John Doe”, company: “tesla” },
{ _id: 155, name: “Joe Jones”, company: “google” },
{ _id: 156, name: “Alon Gal”, company: “tesla” },
]
I know I can use the $lookup operation in order to fetch the right document during a query but I was wondering if it’s possible to run some “updateMany” function to add another field to the companies collection in order to get the following results:
[
{ _id: 1, name: “tesla”, location: “somewhere” employees: [{name: “Alon Gal”}, {name: “John Doe”}]},
{ _id: 2, name: “google”,location: “somewhereElse” }
]
So basically make some “match” between two fields in two different collections that share the same value (company field in employees collection and name field in companies collection in this case) and update one of these collections accordingly.
I know also about DBrefs but it seems that I need to know the document’s _id and this is not the case here since I want to make the match according to another field’s value.