Joining collections in MongoDB

For the purposes of this article, I have created a collection called mongo2 and have furnished it with one of the records from the mongo collection, to ensure we get a join match.

We can then run the below command:

db.mongo.aggregate([ { $lookup: { from: “mongo2”, localField: “name”, foreignField: “name”, as: “new_join” } } ]).forEach(printjson)

Let’s step through this:

  • from: “mongo2” is the table we will extract the matched record from
  • localField: “name” is the field in mongo
  • foreignField: “name” is the field in mongo2
  • as: “new_join” is the name of the field into which the array of join details will be stored.

In SQL, this statement would be written as:

SELECT * FROM MONGO LEFT JOIN MONGO2 ON MONGO.NAME = MONGO2.NAME

Kodey