Home > database >  how to retrieve records which didn't have a particular property in mongodb
how to retrieve records which didn't have a particular property in mongodb

Time:10-05

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

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

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

CodePudding user response:

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

  • Related