GabrielCard
GabrielCard

Reputation: 317

How do I use find () in mongodb with a conditional to use one field or another?

I have to return documents that are between two dateTime values ​​or if the dateTime field does not exist, use the createdAt field. I'm using this query:

{ dateTime: { $gte: 1554087600000, $lte: 1609431033000 } }

But sometimes the dateTime field doesn't exist, so in this case, I have to use the createdAt field.

Upvotes: 2

Views: 735

Answers (1)

J.F.
J.F.

Reputation: 15177

If I understood correctly, you can use $or to filter by one value or another and $and with $exists to ensure the query will be fetch docuemtns where dateTime does not exist:

This query will get dateTime values if the are betwwen $gte and $lte specified or will get the document where dateTime does not exists and createdAt field match the criteria $gte/$lte.

db.collection.find({
  "$or": [
    {
      "dateTime": {"$gte": 1,"$lte": 2}
    },
    {
      "$and": [
        {"dateTime": {"$exists": false},},
        {"createdAt": {"$gte": 1,"$lte": 2}}
      ]
    }
  ]
})

Example here

Upvotes: 2

Related Questions