在MongoDB中查询数组中的嵌入文档

时间:2018-02-05 04:31:06

标签: mongodb mongodb-query

我将此子文档嵌入到数组中:

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

如何选择仅匹配

的车辆
{vehicle:'Honda', Model:'Civic'}

因此:

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

2 个答案:

答案 0 :(得分:1)

给出这样的文件:

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

以下查询使用$elemMatch 查询运算符仅查找具有vehicle:'Honda' and Model:'Civic'的文档:

db.collection.find(
    { company: { $elemMatch: { vehicle: 'Honda', Model: 'Civic' } } }
)

如果您只想返回包含vehicle:'Honda' and Model:'Civic'的公司数组中的第一个元素,那么您应该使用$elemMatch 投影运算符

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"
        }
    ]
}

来自文档:

  

$elemMatch运算符匹配包含数组字段的文档,其中至少有一个元素符合所有指定的查询条件。

  

$elemMatch运算符将查询结果中<array>字段的内容限制为仅包含与$elemMatch条件匹配的第一个元素。

答案 1 :(得分:0)

find()关键字需要用于特定元素:

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