【发布时间】:2020-03-21 16:00:59
【问题描述】:
我有 2 个集合,“业务”和“评论”:
// business row example
{
"_id" : ObjectId("5ddbc3c1a94f7aac8d179b7c"),
"business_id" : "vcNAWiLM4dR7D2nwwJ7nCA",
"full_address" : "4840 E Indian School Rd\nSte 101\nPhoenix, AZ 85018",
"hours" : {
"Tuesday" : {
"close" : "17:00",
"open" : "08:00"
},
"Friday" : {
"close" : "17:00",
"open" : "08:00"
},
"Monday" : {
"close" : "17:00",
"open" : "08:00"
},
"Wednesday" : {
"close" : "17:00",
"open" : "08:00"
},
"Thursday" : {
"close" : "17:00",
"open" : "08:00"
}
},
"open" : true,
"categories" : [
"Doctors",
"Health & Medical"
],
"city" : "Phoenix",
"review_count" : 7,
"name" : "Eric Goldberg, MD",
"neighborhoods" : [],
"longitude" : -111.983758,
"state" : "AZ",
"stars" : 3.5,
"latitude" : 33.499313,
"attributes" : {
"By Appointment Only" : true
},
"type" : "business"
}
// review example
{
"_id" : ObjectId("5ddbc3ea9d4415aa1e6696ae"),
"votes" : {
"funny" : 0,
"useful" : 0,
"cool" : 0
},
"user_id" : "KBLW4wJA_fwoWmMhiHRVOA",
"review_id" : "dNocEAyUucjT371NNND41Q",
"stars" : 4,
"date" : "2012-03-02",
"text" : "Been going to Dr. Goldberg for over 10 years. I think I was one of his 1st patients when he started at MHMG. He's been great over the years and is really all about the big picture. It is because of him, not my now former gyn Dr. Markoff, that I found out I have fibroids. He explores all options with you and is very patient and understanding. He doesn't judge and asks all the right questions. Very thorough and wants to be kept in the loop on every aspect of your medical health and your life.",
"type" : "review",
"business_id" : "vcNAWiLM4dR7D2nwwJ7nCA"
}
我想计算每个企业平均获得多少颗星,并按该值降序排序。到目前为止,我得到了:
db.getCollection('review')
.aggregate
([
{
$group:
{
_id: "$business_id",
avgStars: {$avg: "$stars"}
}
},
{
$lookup:
{
from: "business",
localField: "_id",
foreignField: "business_id",
as: "business_data"
}
},
{$unwind: "$business_data"},
{$project: {"name": "$business_data.name", "avgStars": "$avgStars"}},
//{$sort: {avgStars: -1}}
])
如果没有注释部分,它就可以工作 - 让我得到 (_id, name, avgStars) 的列表。当我取消注释 $sort 函数时,它停止工作 - Robo3T 无限处理。集合只有 50 个元素。为什么排序不起作用?
【问题讨论】:
-
如果是第二阶段(查找之前),排序是否有效?
-
@AlexBlex 是的,但它......很奇怪。我只做了
$group和$sort,在对所有avgStars字段进行排序后,其值为5.0 -
猜测您的集合略大于 50 个元素。
.count()给你什么号码? -
@AlexBlex 是的,你是对的!这些集合实际上每个都有超过 100 万个元素...... Robo3T 非常“友好”地展示了 50 个元素,而没有任何迹象表明还有更多(并且有一些误导性的迹象......)。所以难怪与其他操作进行排序需要这么长时间,谢谢。
标签: mongodb