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"
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐