Categories
JavaScript Answers

How to query referenced objects in Node MongoDB?

Spread the love

To query referenced objects in Node MongoDB, we use $unwind and $lookup.

For instance, we write

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

to call aggregate with $unwind to unwind the $bars entries.

And then we look up the testprop field of the bars entries that’s set to true with $match.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.