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 retrieve records which didn't have a particular property in mongodb

I have a collection like given below and one of the record has isChecked property and other doesn’t. How to retrieve only the records which didn’t have isChecked property or isChecked is false?

{
  _id: new ObjectId("633cdd1ab47cdac0ab830428"),
  url: 'https://www.example.com/1'
}
{
  _id: new ObjectId("633cdd54b47cdac0ab830429"),
  url: 'https://www.example.com/2',
  isChecked: true
}
{
  _id: new ObjectId("633cdd89b47cdac0ab83042a"),
  url: 'https://www.example.com/3'
}

Currently I tried using a cursor which will retrieve all records and loop through it. It works fine but I think there might be an efficient way using aggregate, sadly I’m very new to mongo and started learning it. Any help would be highly appreciated.

Current Code

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

    const cursor = collection.find({});
    const allValues = await cursor.toArray();

    allValues.forEach(data => {
        // logic here
    })

>Solution :

Work with $or operator to check the document is fulfilled with either of these requirements:

  1. isChecked is false

  2. isChecked doesn’t existed via $exists: false

db.collection.find({
  $or: [
    {
      isChecked: false
    },
    {
      isChecked: {
        $exists: false
      }
    }
  ]
})

Demo @ Mongo Playground

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