How to query referenced objects in MongoDB?

Sometimes, we want to query referenced objects in MongoDB.

In this article, we’ll look at how to query referenced objects in MongoDB.

How to query referenced objects in MongoDB?

To query referenced objects in MongoDB, we can use the $lookup operator.

For instance, we write

db.Foo.aggregate(
  { $unwind: "$bars" },
  {
    $lookup: {
      from: "bar",
      localField: "bars",
      as: "bar",
    },
  },
  {
    $match: {
      "bar.testprop": true,
    },
  }
);

to call aggregate with the $lookup property set to an object with the referenced object properties we’re looking for.

We look for the collection specified with $lookup.from.

We look for the localField in the field specified in $lookup.from and we return the result in the field with the name set as the value of as.

We look for the field values in the $bars array since we set unwind to $bars.

And we search for the items with bar.testprop set to true with $match.

Conclusion

To query referenced objects in MongoDB, we can use the $lookup operator.