0

i have the following document in a collection:

{
    "_id" : 101,
    "students" : [ 
        {
            "name" : "john",            
            "age" : 10,
            "city":'CA'
        },
        {
            "name" : "danial",            
            "age" : 15,
            "city":'KA'
        }
    ]
}

{
    "_id" : 102,
    "students" : [ 
        {
            "name" : "adam",            
            "age" : 20,
            "city":'NY'
        },
        {
            "name" : "johnson",            
            "age" : 12,
            "city":'CA'
        }
    ]
}

And i fire the following query:

db.data.find({'students.city':'CA'})

This returns me "students" objects from both the documents, as one instance matches the filter ("city"; 'CA') in both.

However, i desire to only get the matching array in the result. That is, i want the following result:

{
    "_id" : 101,
    "students" : [ 
        {
            "name" : "john",            
            "age" : 10,
            "city":'CA'
        }
    ]
}

{
    "_id" : 102,
    "students" : [        
        {
            "name" : "johnson",            
            "age" : 12,
            "city":'CA'
        }
    ]
}

Please help.

2 Answers 2

3

You need to use $elemMatch in your projection:

> db.data.find({'students.city':'CA'},{ students:{ $elemMatch:{'city':'CA'} }})
{ "_id" : 101, "students" : [ { "name" : "john", "age" : 10, "city" : "CA" } ] }
{ "_id" : 102, "students" : [ { "name" : "johnson", "age" : 12, "city" : "CA" } ] }

Btw: I'd strongly suggest reading the Open letter to students with homework problems.

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

Comments

0

I think you should use an aggregation operation.

Here you have the documentation: https://docs.mongodb.org/manual/aggregation/

And a similar question: Retrieve only the queried element in an object array in MongoDB collection

4 Comments

Nope, that's plainly wrong. See my answer.
yep. you are right. after confirming again. it's better your way. Correct me if I'm wrong: I said to use aggregate because I thought you cannot return multiple elements of an array matching your criteria using a find() operation. but since it's different documents and only 1 matching element per document.your way it's the right one.
I haven't checked, but I think it could be possible to use an "$or" in the projection...
@MarkusWMahlberg i tried to use $or inside the $elemMatch to return multiple elements, but it was not working.

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.