Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays MongoDB对象数组查询_Arrays_Mongodb_Object - Fatal编程技术网

Arrays MongoDB对象数组查询

Arrays MongoDB对象数组查询,arrays,mongodb,object,Arrays,Mongodb,Object,我有一个这样的用户数据库: { "_id": 1, "name": "Carlo", "cars": [{ "type": "sport", "score": 10 }, { "type": "hatchback", "score": 5 }, { "type": "family", "score": 4 }, { "type": "family", "score": 3 }] } 如何选择掀背车得分超过6分的所有用户? 所以,查

我有一个这样的用户数据库:

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

如何选择掀背车得分超过6分的所有用户? 所以,查询必须在cars数组中找到某个对象,该对象的属性“type”的值“hatchback”和“score”大于6,您可以使用该属性来执行此操作。这是一个工作样本

db.getCollection('users').find(
    {"cars": 
        {$elemMatch: 
            { "type": "hatchback","score": {$gte: 6}
            }
        }
    }
)
正如您所看到的,$elemMatch的语法是

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
这里你的数组字段是cars。 由于您需要匹配类型=掀背车且分数大于或等于6, 您的查询将是{type:hatchback,score:{$gte:6}。希望这对您有所帮助