Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
MongoDB: Search for a string in a collection and return only matched collection items

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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 } )
over 4 years ago · Santiago Trujillo Report

0

$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/

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!