0

I have a database of users like this:

{
"_id": 1,
"name": "Carlo",
"cars": [{
    "type": "sport",
    "score": 10
}, {
    "type": "hatchback",
    "score": 5
}, {
    "type": "family",
    "score": 4
}, {
    "type": "family",
    "score": 3
}]

}

How can I choose all of the users whose hatchback has score more than 6? So, query has to find in array of cars some object, which has a property 'type' with value 'hatchback' and 'score' more than 6

Leonid Gordun
  • 361
  • 1
  • 4
  • 14

1 Answers1

1

Hi you can use $elemMatch to do this. here is a working sample

db.getCollection('users').find(
    {"cars": 
        {$elemMatch: 
            { "type": "hatchback","score": {$gte: 6}
            }
        }
    }
)

As you can see you the syntax of $elemMatch is

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

Here your array field is "cars". Since you need match on type = hatchback and score greater than or equal to 6, your query would be { "type": "hatchback","score": {$gte: 6}. Hope this helps.

Samip Suwal
  • 1,253
  • 11
  • 17