node.js - Mongoose - 为字段的每个唯一值计算文档
问题描述
这是我的架构
位置架构
const locationSchema = mongoose.Schema({
name : { type: String, required: true },
description : { type: String, required: true },
cover_pic: { type: String},
address : {
line_1:{ type: String, required: true},
line_2: { type: String },
city: { type: String, required: true },
state_ut: { type: String, required: true },
zipcode: { type: Number, required: true }
},
loc:{
type:{ type: String},
coordinates:[]
},
phone_number : { type: Number },
location_type : { type: String },
location_website : { type: String }
})
审查架构
const reviewSchema = mongoose.Schema({
rating: {type: Number, require: true, min: 1, max: 5},
review: {type: String, require: true},
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true },
locationId: { type: mongoose.Schema.Types.ObjectId, ref: 'Location' ,required: true }
})
reviewSchema.index({ user: 1, location: 1 }, { unique: true });
如何获取特定位置的每颗星的总计数?
例如,我想从集合中获取 aLocation
的评分,所需的输出将类似于:_id
Review
{
"5 stars": 10,
"4 stars": 15,
"3 stars": 8,
"2 stars": 7,
"1 stars": 8
}
解决方案
您可以使用 MongoDB 的聚合 API,特别是$group 运算符。
var ratings = {};
Review.aggregate([
{
$match:
{
locationId: mongoose.Types.ObjectId(loc_id)
}
},
{
$group:
{
_id: "$rating",
count: { $sum: 1 }
}
}
],
function(err, arr) {
arr.map( p => ratings[p._id+" star"] = p.count)
console.log(ratings);
})
此解决方案的灵感来自 MongoDB 文档中的一个示例。
推荐阅读
- c - STM32和ADXL345之间的SPI通信
- javascript - 向下滚动后的开玩笑测试没有找到元素
- html - 有没有办法恢复/取消特定区域的背景过滤器?
- keras - Keras / NLP为文本序列中的位置分配权重/更高优先级?
- html - 如何从 HTML 中提取和保存 SVG?
- matlab - 如何在MATLAB中的特定点找到传递函数的幅度和相位
- python - 如何在python3中的fstring中包含关键字
- ruby-on-rails - 从灵活的库存集中有效地选择
- sympy - Sympy多元不等式在某个范围内求解一个变量与另一个变量
- python - 在将对象传递给 python 类方法时需要帮助