有两个mongoose模式
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查询来根据评论数量查找名著呢?
因此,编写find查询根据特定图书上的评论数量(其中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
}发布于 2016-11-26 02:15:56
我创建了一个小集合
>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做过滤器。如果需要,可以将其包含在查询中,即
https://stackoverflow.com/questions/40810180
复制相似问题