0

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

2

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.

  • The majority of the time I'll need to do both queries as the first won't find anything so I think I'll stick with an $or. – Sean Bannister Jul 1 '12 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.