Skip to main content

MongoDB: $lookup or not $lookup?

As developers, we always try to make our database queries as fast as possible. For this we use various schemas, structures, relations. But still, sometimes we need to combine information taken from several sources (collections, tables, etc.). In this article I will try to describe possible ways of collecting data from different collections of MongoDB

Tools

  1. MongoDB v4.0.3 used (module “mongodb-memory-server”) ― replica set
    https://www.npmjs.com/package/mongodb-memory-server
  2. Using MongoDB driver v3.3.4 (module “mongodb”)
    https://www.npmjs.com/package/mongodb
  3. “microseconds” module
    https://www.npmjs.com/package/microseconds

Task

We have data in 3 collections: “teachers”, “students” and “exams”

Before start

Let’s create “teachers”, “students” and “exams” collections

Way 1: Multiple requests (bad but works)

We can get all teachers -> then students for each teacher -> then exams for each student -> and finally filter only “passed” exams

Way 2: Get whole collections (bad but depends)

We can get all teachers -> get all students -> get exams and combine the data in code

Way 3: Aggregate (let MongoDB do it’s job)

We can get teachers -> aggregate data from “students” collection by “teacherId” -> aggregate data from “exams” collection by “studentId” -> add/remove needed/not needed fields.
For all of this we can use MongoDB’s “aggregate” method
  1. Second “$lookup” gets data from “exams” collection by “studentId” (in current documents “studentIds” are in “students” array but MongoDB understands us and checks every “_id” in array) and puts it into “exams” array
  2. “$project” used for removing unnecessary data (“students” array is not needed anymore)
  3. Than we need to get only “passed” exams. For this we’ll filter “exams” array and put filtered values in new field “examsPassedArray” (with “$addFields”)
  4. We need only the number of passed exams ($size of “examsPassedArray”) and _id of teacher (_id passes $project stage of aggregation by default)

Just for information (result may vary)

Conclusion

Instrument provided by a service in most cases are the best for the service.
So don’t forget to check official documentation

Comments