Mankind1023
Mankind1023

Reputation: 7732

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'
        }
    },    
])

Upvotes: 1

Views: 1320

Answers (1)

varman
varman

Reputation: 8894

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

Upvotes: 1

Related Questions