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}。希望这对您有所帮助