Meteor.js

How to do aggregation with $lookup in Meteor & MongoDB

How to do aggregation with $lookup in Meteor & MongoDB?

The schema

Imagine we have collection data into MongoDB something like that

authors

[
  {
    "_id" : "5c80d00b3fbdcccfa8fe5cb8",
    "name" : "Shabbir",
    "profession" : "Dev",
    "address" : {
      "street" : "Main"
    }
  }
  {
    "_id" : "5c80d00b3fbdcccfa8fe5cb9",
    "name" : "Senior Sakib",
    "profession" : "Dev",
    "address" : {
      "street" : "Sub"
    }
  }
]
books
[
  {
    "_id" : "5c80cf58a80135836586b5eb",
    "name" : "Ruby"
  },
  {
    "_id" : "5c80cf58a80135836586b5eb",
    "name" : "Meteor"
  },
  {
    "_id" : "5c80cf58a80135836586b5eb",
    "name" : "React.js"
  }
]

authorBooks

[
   {
     "_id" : "5c80cf58a4458653433b5eb",
     "authorId" : "5c80d00b3fbdcccfa8fe5cb8",
     "bookId" : "5c80cf58a80135836586b5eb"
   },
   {
     "_id" : "5c80cf58a76685642323b5eb",
     "authorId" : "Meteor",
     "bookId" : "5c80cf58a80135836586b5eb"
   }
]

Now how we fetch the data in meteor environment for reference such which author responsible for which book, if we use mongo shell with aggregate framework then we could something like that

db.authorBooks.aggregate(
[
  {
    $lookup: {
      from: "authors",
      localField: "authorId",
      foreignField: "_id",
      as: "authors"
    }
  },
  {
    $lookup: {
      from: "books",
      localField: "bookId",
      foreignField: "_id",
      as: "books"
    }
  }
]
).pretty()

but we are using Meteor.js & Meteor.js not supported the aggregate framework, so what we could then.

It’s very easy we will install aggregate framework which has in atmosphere js such as meteor add meteorhacks:aggregate but the MongoDB library has changed the way aggregations are returned and the meteorhacks:aggregate package is unmaintained, so has not kept pace.
However, the AggregationCursor object has a toArray() method, which returns a Promise to the result we’re expecting. We should be able to use something like:

import { Promise } from 'meteor/promise';
 const authorBooks = Promise.await(AuthorBooks.aggregate([
{
  $lookup: {
    from: "authors",
    localField: "authorId",
    foreignField: "_id",
    as: "authors"
  }
},
{
  $lookup: {
    from: "books",
    localField: "bookId",
    foreignField: "_id",
    as: "books"
  }
}
]).toArray());
console.log(authorBooks);

Here we go!


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *