Filtering by referenced document property in the MongoDB

Taking advantage of the “1 to N bidirectional relationship in the MongoDB” post, I intend to show you how to “make a cross join” with MongoDB and filter by a┬áreferenced document property.

I’ll use all that code and add another endpoint to the API. This new endpoint will GET the comments where the BlogPost title contains some word.

Let’s go to code:

// GET COMMENTS BY BLOG ENTRY TITLE
router.get('/comments/:page/:blogPostTitle', function(req, res) {
    Comment
        .aggregate([
        // join BlogPost collection
        {
            $lookup: {
                from: 'blogposts', // special attention here, it is the name of the collection
                localField: 'BlogPost',
                foreignField: '_id',
                as: 'BlogPost'
            }
        },
        // convert array of BlogPost to object
        {
            $unwind: '$BlogPost'
        },
        // filter
        {
            $match: 
            { 
                "BlogPost.Title": new RegExp(req.params.blogPostTitle) 
            }
        },
        // pagination info
        { $sort: { "BlogPost.Title": 1 } },
        { $skip: (req.params.page * 10) - 10 }, // (page index * page size) - page size
        { $limit: 10 }
        ])
        .exec(function(err, entities) {
            if (err)
                res.send(err);

            res.json(entities);
        });
});

Now I’ll explain some points:

  1. This endpoint will receive “page” and “blogPostTitle” parameter.
  2. We will use the “aggregate()” method instead of “find()”.
  3. In the “$lookup” we will relate the property “BlogPost” with de collection of documents “blogposts”. Pay attention in the capitalizations here! The collection name has to be the same that you will find into mongodb.
  4. The “$lookup” will build an object. “$unwind” will transform that in an array!
  5. Now we are able to filter a property from that array.
  6. For curiosity I added a pagination and sort mechanism.
  7. And I also use RegExp, so is it possible build complex regular expressions to filter.

And now, the result:

I think the scenarios like that can be common, and I hope that tip can be useful.

I hope you enjoyed it!

GitHub

Spaki.

With more than 15 years of experience developing softwares and technologies, talking about startups, trends and innovation, today my work is focused to be CTO, Software Architect, Technical Speaker, Technical Consultant and Entrepreneur.

From Brazil, currently lives in Portugal working at https://www.farfetch.com as Software Architect, besides to keep projects in Brazil, like http://www.almocando.com.br/

Share

1 thought on “Filtering by referenced document property in the MongoDB”

Leave a Reply

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