Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading