Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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