2016-11-25 69 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給的? –