Skip to content
Advertisement

How to query based on a field in a referenced document in mongodb

I have two MongoDB collections. First is Products, and the seconds is Users. The product documents has a field ownerId which refers to the users collection and the user has a Boolean field isActive.

What I want to do is to find all the products where their users are active using Mongoose method collection.find(). I don’t know if i can do that querying only the products collection . Any help please ?

Advertisement

Answer

If you only store user’s reference in the products documents, you would have to use aggregate query:

  • $lookup – to populate owner property with the actual user data.
  • $match – to filter only the documents where owner’s isActive property is equal to true.
db.products.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "ownerId",
      "foreignField": "_id",
      "as": "owner"
    }
  },
  {
    "$match": {
      "owner.isActive": true
    }
  }
])

Working example

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement