user13000875
user13000875

Reputation: 495

Conditional query in mongoose

Sample Document

[
  {
    "_id": ObjectId("612b5d4bbc1bed7ce5d5oa66"),
    "username": "test",
    "user_details": {}
  },
  {
    "_id": ObjectId("612b5d4bbc1bed7ce5d5oa67"),
    "username": "test",
    "user_details": {
      "name": "Test",
      "addreess": "tets addr",
      "city": "nddj"
    },
    verify_at: ISODate("2021-08-30T10:23:37.558Z")
  }
]

I want to fetch those record if user_details is empty object then verify_at should not exist and user_details object has some value then no need to check verify_at exists false This is what I have tried

 $and:[{$or:[{$and:[{user_details:{}},{verify_at:{$exists:false}}]},{$and:{user_details:{$ne:{}}}}]}]

Upvotes: 0

Views: 364

Answers (1)

J.F.
J.F.

Reputation: 15177

If I've understood correctly you can use this query:

  • If user_details exists -> Find the element without check verify_at
  • If user_details is {} then check if verify_at does not exists.
yourModel.find({
  "$or": [
    {
      "user_details": {
        "$ne": {}
      }
    },
    {
      "$and": [
        {
          "user_details": {}
        },
        {
          "verify_at": {
            "$exists": false
          }
        }
      ]
    }
  ]
})

Example here

Upvotes: 1

Related Questions