mongodb - 如何根据 MongoDB 中的列表计数过滤文档?
问题描述
在 MongoDB 中,我正在寻找至少包含 5 条餐厅评论的文档。我尝试在 $match 上添加过滤器,例如:
{"grades.score: {$gt: 4}}
但是,这将为我提供评论评分至少为 5 或更高的文档,而我想要的是评论计数至少为 5。
db.restaurants.aggregate([
... {"$match":
... {"$and":[
... {"borough":"Bronx"},
... { "cuisine": "American "},
... {"address.zipcode":"10467"}]}},
... {"$group":
... {"_id":
... {"name" : "$name",
... "grades.score" : "$grades.score"}}}])
这就是我得到的:
{ "_id" : { "name" : "Zymi Bar & Grill", "grades.score" : [ 75, 5, 18 ] } }
{ "_id" : { "name" : "Allerton Diner", "grades.score" : [ 20, 9 ] } }
{ "_id" : { "name" : "Gasolina Bar Lounge", "grades.score" : [ 10, 10 ] } }
{ "_id" : { "name" : "Salud Y Estilo De Vida", "grades.score" : [ 0, 7, 7, 6 ] } }
{ "_id" : { "name" : "Coffee Shop", "grades.score" : [ 20, 12, 12, 9, 2 ] } }
{ "_id" : { "name" : "Nicky'S Coffee Shop", "grades.score" : [ 7, 9, 12, 13, 3 ] } }
{ "_id" : { "name" : "John'S Luncheonette", "grades.score" : [ 5, 5, 8, 12, 11 ] } }
{ "_id" : { "name" : "Kennedy'S Chicken & Pizza", "grades.score" : [ 7 ] } }
{ "_id" : { "name" : "V.I.P.'S Cafe", "grades.score" : [ 9, 11, 17, 7, 23, 9 ] } }
{ "_id" : { "name" : "Woodlawn Cafe", "grades.score" : [ 5, 13, 12, 11, 27, 2 ] } }
{ "_id" : { "name" : "Moshulo Golf Course", "grades.score" : [ 11 ] } }
{ "_id" : { "name" : "Kennedy Fried Chicken", "grades.score" : [ 4, 9, 5, 9 ] } }
{ "_id" : { "name" : "Kennedy'S Chicken And Pizza", "grades.score" : [ 9, 19, 13, 12, 26 ] } }
{ "_id" : { "name" : "502 Bar Lounge", "grades.score" : [ 4, 4, 2, 0 ] } }
{ "_id" : { "name" : "Burger Barn Restaurant", "grades.score" : [ 8, 9, 11, 16, 19 ] } }
这就是我需要的:
{ "_id" : { "name" : "Coffee Shop", "grades.score" : [ 20, 12, 12, 9, 2 ] } }
{ "_id" : { "name" : "Nicky'S Coffee Shop", "grades.score" : [ 7, 9, 12, 13, 3 ] } }
{ "_id" : { "name" : "John'S Luncheonette", "grades.score" : [ 5, 5, 8, 12, 11 ] } }
{ "_id" : { "name" : "V.I.P.'S Cafe", "grades.score" : [ 9, 11, 17, 7, 23, 9 ] } }
{ "_id" : { "name" : "Woodlawn Cafe", "grades.score" : [ 5, 13, 12, 11, 27, 2 ] } }
{ "_id" : { "name" : "Kennedy'S Chicken And Pizza", "grades.score" : [ 9, 19, 13, 12, 26 ] } }
{ "_id" : { "name" : "Burger Barn Restaurant", "grades.score" : [ 8, 9, 11, 16, 19 ] } }
解决方案
您可以根据您的示例尝试此操作:
db.restaurants.aggregate([{
"$match": {
"$and": [{
"borough": "Bronx"
},
{
"cuisine": "American "
},
{
"addresszipcode": "10467"
}
]
}
},
{
"$group": {
"_id": {
"name": "$name",
"score": "$grades.score",
}
}
},
{
$match: {
$expr: {
$gte: [{
$size: "$score"
}, 5]
}
}
}
])
使用最终的 $match 和 $expr 来执行聚合表达式