首页 > 解决方案 > 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的评分,所需的输出将类似于:_idReview

{
  "5 stars": 10,
  "4 stars": 15,
  "3 stars": 8,
  "2 stars": 7,
  "1 stars": 8
}

标签: node.jsmongodbmongoose

解决方案


您可以使用 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 文档中的一个示例


推荐阅读