How to join tables in MongoDB using DBRef

This is like a personal note about joining tables in MongoBD.

If your collection looks like this:

// posts collection
{ _id: 1, title: 'My Parent', parent: null }
{ _id: 2, title: 'My Post', parent: DBRef<posts._id=1> }

And you want to consume data like this:

// posts collection
{ _id: 1, title: 'My Parent', parent: null }
{ _id: 2, title: 'My Post', parent: { _id: 1, title: 'My Parent', parent: null } }

In this example I'm joining data from the same table, but you can do it from different tables.

DBRef is not recommended, but in case you still use it.

This is the code that can help you:

const postsDb = db.collection('posts');

const posts = postsDb
    .aggregate([
      {
        $lookup: {
          from: 'posts',
          localField: 'parent.$id',
          foreignField: '_id',
          as: 'parent',
        },
      },
      {
        $unwind: {
          path: '$parent',
          preserveNullAndEmptyArrays: true, // keeps the documents even if "parent" is null or an empty array
        },
      },
      { $match: findPost },
      {
        $sort: { created: -1 },
      },
    ])
    .toArray();