简体   繁体   中英

Mongoose - Count documents for each unique value of a field

Here are my Schemas

Location Schema

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 }
})

Review Schema

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 });

How do I fetch total number of counts of each star of a particular location?
For example, I want to fetch ratings of a Location with respect to _id from Review collection and the desired output will be something like:

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

You can use the aggregation API of MongoDB, the $group operator in particular.

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);
})

This solution is inspired from an example in MongoDB docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM