Anup
Anup

Reputation: 9738

MongoDB - Returning only matching Array from Object

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.

Upvotes: 0

Views: 2911

Answers (2)

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20683

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.

Upvotes: 3

Telmo Ivo
Telmo Ivo

Reputation: 4328

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

Upvotes: 0

Related Questions