MongoDB中的迭代cursor项目练习

该项目涉及使用MongoDB对bookshop.js文件中的数据进行迭代操作,以统计不同类型的出版物数量以及每本书的关键字总数。通过游标迭代,分别计算了书籍、杂志、音乐CD和杂志的总数,并输出了相应结果。同时,遍历每本书,若存在关键字则输出标题及关键字数量,否则显示标题及关键字数为0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MongoDB Iterations over a cursor

项目介绍

我们拥有一个bookshop.js的文件,将文件导入的MongoDB后按照要求数据操作工作。

练习用的bookshop.js已被上传到我的资源。
https://download.youkuaiyun.com/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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值