Tutorials References Exercises Videos Menu
Create Website Get Certified Upgrade

MongoDB Aggregation $lookup


Aggregation $lookup

This aggregation stage performs a left outer join to a collection in the same database.

There are four required fields:

  • from: The collection to use for lookup in the same database
  • localField: The field in the primary collection that can be used as a unique identifier in the from collection.
  • foreignField: The field in the from collection that can be used as a unique identifier in the primary collection.
  • as: The name of the new field that will contain the matching documents from the from collection.

Example

In this example, we are using the "sample_mflix" database loaded from our sample data in the Intro to Aggregations section.

db.comments.aggregate([
  {
    $lookup: {
      from: "movies",
      localField: "movie_id",
      foreignField: "_id",
      as: "movie_details",
    },
  },
  {
    $limit: 1
  }
])
Try it Yourself »

This will return the movie data along with each comment.