MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mongoose/Mongodb Aggregate - gruppieren und mitteln Sie mehrere Felder

Das hat bei mir funktioniert:

  Post.aggregate([
    { $group: { _id: "$date", avgRating: { $avg: '$rating' }}}
  ]).
  then(function (res) {
    console.log(res); 
  })

Ausgabe:

[
  { _id: 'Aug 18, 2021', avgRating: 3.0212234706616727 },
  { _id: 'Aug 19, 2021', avgRating: 2.9680319680319682 },
  { _id: 'Aug 20, 2021', avgRating: 3.023976023976024 },
  { _id: 'Aug 17, 2021', avgRating: 2.9600665557404326 },
  { _id: 'Aug 21, 2021', avgRating: 3.072661217075386 }
]

ABER es wäre toll, wenn ich das irgendwie anhand anderer Faktoren filtern könnte. Beispielsweise hat jeder Beitrag einen Autor (Verweis auf Benutzermodell). Wie würde ich beim Filtern nach Land, Name oder Geschlecht des Autors vorgehen?

Benutzermodell:

const userSchema = new Schema({
email: {
    type: String,
    required: true,
    unique: true
},
birthday: {
    type: Date,
    required: true,
},
gender:{
    type: String,
    required: true
},
country:{
    name: {
        type: String,
        required: true
    },
    flag: {
        type: String,
        // default: "/images/flags/US.png"
    }
},
avatar: AvatarSchema,
displayName: String,
bio: String,
coverColor: {
    type: String,
    default: "#343a40"
},
posts: [ 
    {
    type: Schema.Types.ObjectId,
    ref: "Post" 
    }
],
comments: [
    {
        type: Schema.Types.ObjectId,
        ref: "Comment"
    }
],
postedToday: {
    type: Boolean,
    default: false
},
todaysPost: {
    type: String
}
}) 

Etwas in der Art

    Post.aggregate([
    {$match: {"date": today}},
    {$group: {_id: {"country": "$author.country.name"}, avgRating: {$avg: "$rating"}}}
]).then(function(res) {
    console.log(res)
})