猫鼬-计算文档中每个字段的唯一值

时间:2020-05-13 15:39:11

标签: node.js mongodb 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 });

如何获取特定位置的每颗恒星的总数?
例如,我想从Location集合中获取关于_id的{​​{1}}的评级,并且所需的输出将类似于:

Review

1 个答案:

答案 0 :(得分:1)

您可以使用MongoDB的聚合API,尤其是$group operator

committed-a-first-time

此解决方案的灵感来自MongoDB文档中的example