Home > Net >  How to query based on a field in a referenced document in mongodb
How to query based on a field in a referenced document in mongodb

Time:10-25

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 ?

CodePudding user response:

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

  • Related