1

I have the following records:

Record 1:  
{
    "status": "active",
    "users": [
        {
            "name": "foo",
            "status": "a"
        },
        {
            "name": "foo",
            "status": "b"
        }        
    ]
}

Record 2:  
{
    "status": "active",
    "users": [
        {
            "name": "bar",
            "status": "a"
        },
        {
            "name": "foo",
            "status": "b"
        }        
    ]
}

Now, I wish to return only those records in which the user.name is "foo" and the user.status is "a" - That is I need to get Record 1 back since it satisfies my requirements.

How do I do the AND operation on the array within the record to achieve this? I tried the following query:

{
    "$and": [
        {
            "users.name": "foo"
        },
        {
            "users.status": "a"
        }
    ]
}

but I get both the records - I need only the first record (since in the users array, it has an entry where the name is "foo" AND the status is "a").

Any clues?

2 Answers 2

3

Ok, I found the answer out here

The solution would be to have a query as follows:

{
    "users": {
        "$elemMatch": {
            "name": "foo",
            "status": "a"
        }
    }
}

That did the trick!

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of individual field values you can also use whole objects in find queries. Try:

db.collection.find( { 
    users: {
         "name":"foo",
         "status":"a"
    }
});

This should return all documents where the users array includes an object (or is an object) which looks as described. But note that this doesn't work when the object has additional fields.

2 Comments

So you mean to say that if users array contains objects and these objects contain fields other than name and status, then the above query will not work? In my scenario, yes - the object contains fields other than the two mentioned, but I do not wish to include them in the query - how do I go about it then?
@Philipp please note that your answer won't work correctly - it will only match the exact object {"name":"foo","status":"a"} - it won't even match users that has those two fields in the opposite order!

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.