Given a document like this:
{
"_id" : ....,
"company" : [
{
"vehicle" : "Toyota",
"Model" : "Camry"
},
{
"vehicle" : "Honda",
"Model" : "Civic"
},
{
"vehicle" : "Honda",
"Model" : "Accord"
},
{
"vehicle" : "Mercedes",
"Model" : "vboot"
}
]
}
The following query uses the $elemMatch query operator to find only those documents having vehicle:'Honda' and Model:'Civic':
db.collection.find(
{ company: { $elemMatch: { vehicle: 'Honda', Model: 'Civic' } } }
)
If you only want to return the first element in the company array having vehicle:'Honda' and Model:'Civic' then you should use the $elemMatch projection operator:
db.collection.find(
// only find documents which have a company entry having vehicle=Honda and model=Civic
{ company: { $elemMatch: { vehicle: 'Honda', Model: 'Civic' } } },
// for the documents found by the previous clause, only return the first element
// in the company array which has vehicle=Honda and model=Civic
{ company: { $elemMatch: { vehicle: 'Honda', Model: 'Civic' } } }
)
// returns:
{
"_id" : ObjectId("5a79613f85c9cec3a82c902c"),
"company" : [
{
"vehicle" : "Honda",
"Model" : "Civic"
}
]
}
From the docs:
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
The $elemMatch operator limits the contents of an <array> field from the query results to contain only the first element matching the $elemMatch condition.
$elemMatch, why vehicle array has no key?