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 } )
$elemMatch operator returns only first element matching the $elemMatch condition in query result.
Please try executing following query
db.geo.find({
features: {
$elemMatch: {
"properties.TYPE": "8003"
}
}
}, {
features: {
$elemMatch: {
"properties.TYPE": "8003"
}
}
})
Please refer the documentation of $elemMatch operator as described in below mentioned URL
https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/