Take the 2-minute tour ×
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. It's 100% free, no registration required.

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

1 Answer 1

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

 
discard

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.