1. 程式人生 > 其它 >MongoDB中的迭代cursor專案練習

MongoDB中的迭代cursor專案練習

技術標籤:資料庫系統mongodbcursor迭代器

MongoDB Iterations over a cursor

專案介紹

我們擁有一個bookshop.js的檔案,將檔案匯入的MongoDB後按照要求資料操作工作。

練習用的bookshop.js已被上傳到我的資源。
https://download.csdn.net/download/Jifu_M/14159088.

下面列出的查詢必須通過cursor上的迭代來實現:

(a) 在書店資料庫中列出圖書(書籍、雜誌、音樂cd和雜誌)的型別和每種型別的圖書總數。

(b) 列出每本書的標題和關鍵字總數。如果一本書沒有關鍵字,那麼關鍵字的總數必須為0。

專案開始

首先要建立一個資料夾來進行專案,之後啟動MongoDB,最後讀取檔案:

mkdir DATA

mongod –dbpath DATA –port 4000

mongo –port 4000

load("bookshop.js");

(a)

var counters = [0,0,0,0];
var it = db.bookshop.find();
while(it.hasNext()){
    var find = it.next();
    if(find.book){
        counters[0]++;

    }
    if(find.journal)
{ counters[1]++; } if(find.musicCD){ counters[2]++; } if(find.magazine){ counters[3]++; } }; printjson("Type: book , Total number of book: "+counters[0]); printjson("Type: journal , Total number of journal: "+counters[1]); printjson
("Type: musicCD , Total number of musicCD: "+counters[2]); printjson("Type: magazine , Total number of magazine: "+counters[3]);

輸出結果如下:

> printjson("The number of book is: " + counter[0]);
"The number of book is: 4"
> printjson("The number of journal is: " + counter[1]);
"The number of journal is: 7"
> printjson("The number of musicCD is: " + counter[2]);
"The number of musicCD is: 3"
> printjson("The number of magazine is: " + counter[3]);
"The number of magazine is: 2"

(b)

var it2= db.bookshop.find();
while (it2.hasNext()) {
    var find = it2.next();
    if(find.book){
                  if(find.book.keywords){
                  printjson("Title :" +find.book.title+"  The total number of keywords: "+find.book.keywords.length);
                                         }
                  else{
                   printjson("Title :" +find.book.title+"  The total number of keywords: "+0);
                       }
}};

輸出結果如下:

"Database Systems ; The number of keywords: 3"
"Core Java ; The number of keywords: 3"
"Algorithms ; The number of keywords: 0"
"C++ Programming ; The number of keywords: 4"