MongoDB: Can I perform a second query if the first doesn’t match

mongodb

When querying MongoDB is it possible to perform a query and if it isn't matched perform a second query. I could perform an $or which will do booth queries and return the results for booth but I only need to perform the second query if the first doesn't match.

Let say my BSON documents look like:

[
  {"id": 1, "value": "foo"},
  {"id": 2, "value": "bar"}
]

I need to return "id": 1 but if it doesn't exist I need to return "id": 2

Best Answer

No, you can't do conditional returns within a single query. You seem to understand that, based on the wording of the question. Maybe if you can explain the exact use case more we might be able to think of another idea.

With the general description you give, I would just make two round trips to the server, if you'd usually find something the first try. Or do an $or, as you mention, if it's more often that you'd return the 2nd option.