Search code examples
mongodblookupprojection

MongoDb - $lookup with where clause


given something like this:

posts:

post: {
 subject: 'test',
 category: 123,
 author: 1
}

users:

{
 id: 1,
 name: 'foo'
}

category:

{
 id: 123,
 name: 'bar'
}

How can I do the equivalent query to the sql:

SELECT * 
FROM posts
JOIN users on posts.author = user.id
JOIN category on posts.category = category.id
WHERE users.name = 'foo' and category.name = 'bar' //this is the problem

I have been experimenting with project / lookups, but I have no idea how to add the 'where' in the lookup itself (or if that is even the proper way to query this.

db.posts.aggregate(
[
    {
        $project: { 'subject': '$subject' },
    },
    {
        $lookup: {
            from: 'users',
            localField: 'author',
            foreignField: 'id',
            as: 'test'
        }
    },    
])

Solution

  • You have to use two $lookup

    [
      {
        "$lookup": {
          "from": "users",
          "localField": "post.author",
          "foreignField": "id",
          "as": "userJoin"
        }
      },
      {
        "$lookup": {
          "from": "category",
          "localField": "post.category",
          "foreignField": "id",
          "as": "categoryJoin"
        }
      },
      {
        $match: {
          "categoryJoin.name": "bar",
          "userJoin.name": "foo"
        }
      }
    ]
    

    Working Mongo playground