0

I have the following documents in the mongoDB

{ "_id" : ObjectId("5215c622f8b2bae39d82b54c"), "params" : { "groupBy" : "days", "country" : "A", "city" : "b" } }
{ "_id" : ObjectId("5215c62df8b2bae39d82b54d"), "params" : { "groupBy" : "days", "country" : "A" } }
{ "_id" : ObjectId("5215c643f8b2bae39d82b54e"), "params" : { "groupBy" : "days" } }

and I tried to find the first document with this query

{params : {groupBy : 'days', country : 'A', 'city' : 'b'}} 

OK, no problem, it works. Let's try this

{params : {groupBy : 'days', city : 'b', country : 'A'}}

and this one do not work surprisingly. OK so now I know order does matter.

I know I can do this to search the first document if I want to ignore the order of attributes.

{ 'params.groupBy' : 'days' , 'params.city' : 'b', 'params.country' : 'A' }

Now consider I want to find the 2nd document and I don't know the order of the attributes before. So what I will do is

{'params.groupBy' : 'days' ,  'params.country' : 'A'}

but this query find both the 1st and the 2nd documents.

So how can I find the 2nd document with only one query?

Edit: One more condition is I am not sure how many attributes will have in the params sub-document in the future and it may keep changing from time to time

4
  • try {params:{groupBy:"days",country:"A"}} Commented Aug 22, 2013 at 8:47
  • but I don't the order before. so I dunno it should be {params:{groupBy:"days",country:"A"}} or {params:{country:"A", groupBy:"days"}} Commented Aug 22, 2013 at 8:49
  • order is matter. in this case your query string should be exactly the same as the subdocument in the document. Commented Aug 22, 2013 at 8:53
  • Is it a requirement that ONLY the second document is found with this query and that the first document is omitted? Easy to find only the first document but the second won't be so easy Commented Aug 22, 2013 at 10:19

1 Answer 1

1

To find the 2nd document with only one query you will need to use the $exists operator.

Your query would look like this:

db.params.find({'params.groupBy': 'days', 'params.country': 'A', 'params.city': {$exists: false}})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. But actually I am not sure how many attributes will have in the params sub-document and it may keep changing from time to time
In that case you need to add that to your question as this answers your initial query of finding the second document in your examples

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.