MongoDB: Search for a channel in a collection and return only matched items

advertisements

I have the following json saved in the mongoDB:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "ID": "1753242",
        "TYPE": "8003"
      }
    },
    {
      "type": "Feature",
      "properties": {
        "ID": "4823034",
        "TYPE": "7005"
      }
    }
  ]
}

When i want to search for a specific TYPE, I can do it like this:

db.geo.find({"features.properties.TYPE":"8003"})

My problem is, that this query returns the whole json and not just elements with the TYPE "8003". Does anybody know, how to retrieve just elements with the TYPE "8003" by query?


With the Mongo db 3.2 release, you can use the new $filter aggregation operator to filter an array during projection, which includes all the matches in the array

db.test.aggregate([
{$match: {'features': {$elemMatch : {"properties.TYPE": '8003' }}},
{$project: {
    features: {$filter: {
        input: '$features',
        as: 'feature',
        cond: {$eq: ['$$feature.properties.TYPE', '8003']}
    }}
}}
]);

If you just want the first element of the results, you can use the positional $ operator like below :

db.geo.find( { "features.properties.TYPE":"8003"}, { "features.$": 1 } )