2016-11-25 68 views
0

排序有两种猫鼬架构MongoDB的聚集和moongoose模式

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

我们如何可以写一个蒙戈查询找到的意见

数的基础上著名的书

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

JSON存储在蒙戈为:

书JSON-

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

评论JSON-

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

} 
+0

你写过任何查询了吗?我的意思是你有没有尝试过某种东西并卡在某个地方 –

+0

'db.comments.aggregate( {$ match:{inEnglish:true}}, {$ group:{_id:{bookId:“$ bookId”},“totalC”:{$ sum:1}}}, {$ sort:{“_id.totalC”:1}})' 我已经试过这个,但它不起作用 – lee

回答

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过滤器:真实。如果你想你可以包括在查询中,

+0

通过上述查询,您将只能找到书籍ID。试试这个查询来获得书的详细信息 ** db.getCollection('comments')。aggregate([0] $ {group:{_id:“$ bookid”,“count”:{$ sum:1}}}, {$ sort:{“count”:-1}}, {$ limit:1}, {$ lookup:{from:“books”,localField:“_id”,foreignField:“_id”,as:“书籍“}} ])** –

+0

这是行不通的 – lee

+0

哪一个是你指的那个我给的还是那个Anish给的? –