在moongoose模式上进行mongodb聚合和排序

时间:2016-11-25 17:43:05

标签: mongodb mongoose mongodb-query mongoose-schema

有两个猫鼬模式

    const bookModel =  new Schema({
    title : String,
    content: String,
    author:{
        id:{
            type: ObjectId,
        },
        name:{
            type: String,
        }
    }
})


const commentModel = new Schema({
    text :String,
    bookid :{ { type : ObjectId , required : true } },
    inEnglish:{
        type: Boolean,
        default:false
    }
})

我们如何根据评论数量编写一个mongo查询来查找着名的书籍

所以,写一个查询来根据特定书籍上的评论数量(其中inEnglish设置为true)对书籍进行排序。

JSON存储在mongo中:

预订JSON -

{
    "_id" :ObjectId(58368df330391521247f6aeb),
    "title": "Dan Brown",
    "content": "COntent of the book" 
}

评论JSON -

{
        "_id" :ObjectId(24568df330391765434f6fgh),
        "text":"Nice Book",
        "bookid":"58368df330391521247f6aeb",
        inEnglish: true

}

1 个答案:

答案 0 :(得分:0)

我创建了一个小集合

>db.comments.find()

{"_id" : ObjectId("58387da2a32c4b96e67ec6b4"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387da8a32c4b96e67ec6b5"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387da9a32c4b96e67ec6b6"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387da9a32c4b96e67ec6b7"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387db0a32c4b96e67ec6b8"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aec", "inEnglish" : true }
{"_id" : ObjectId("58387db2a32c4b96e67ec6b9"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aec", "inEnglish" : true }

现在要预订评论,我运行以下

db.comments.aggregate(
    {$group : {_id : "$bookid", "count" : {$sum : 1}}},
    {$sort : {"count" : -1}},
    {$limit : 1}
)

基本上我正在做的是按书ID分组并获得计数。

我的输出

{ "_id" : "58368df330391521247f6aeb", "count" : 4 }
  

注意:我没有使用inEnglish做过滤器:true。如果您愿意,可以在查询中包含该内容,