yaxx
yaxx

Reputation: 655

Querying an embedded document in an array in MongoDB

I have this subdocument embedded in an array:

 company:{
    products:[
      { vehicle: "Toyota", Model: "Camry" },
      { vehicle: "Honda", Model: "Civic" },
      { vehicle: "Honda", Model: "Accord" },
      { vehicle: "Mercedes", Model: "vboot" },
    ]
 }

How do I select the vehicle that matches only

{vehicle:'Honda', Model:'Civic'}

Thus:

company:{
    products:[         
      { vehicle: "Honda", Model: "Civic" },
    ]
 }

Upvotes: 1

Views: 54

Answers (2)

glytching
glytching

Reputation: 47865

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.

Upvotes: 2

Keshav Pradeep Ramanath
Keshav Pradeep Ramanath

Reputation: 1687

The find() keyword needs to be used for the specific element:

db.company.find({vehicle:"Honda",Model:"Civic"})

Upvotes: 0

Related Questions