NOSQL数据库习题

NOSQL数据库习题

    • 第一章
    • 第二章
    • 第三章
    • 第四章
    • 第五章
    • NoSQL数据库上机测试

第一章

1.写出DB、RDB、DBMS、TRDB、NoSQL、NewSQL、NDFS的中文名称。

答:DB:数据库
RDB:关系型数据库
DBMS:数据库管理系统
TRDB:传统关系型数据库
NoSQL:非关系型数据库
NewSQL: 新式的关系型数据库
NDFS:Hadoop分布式文件系统

2.1) 写出计算机存储数据单位前10个单位的英文简称及与字节单位的换算关系。2)目前大数据级别的入门数据单位为存储单位的哪个级别?

计算机存储数据单位前10个单位的英文简称
B,KB,MB,GB,TB,PB,EB,ZB,YB,BB
字节单位的换算关系:
1B=8Bit
1KB=1024B=2^10B
1MB=1024KB=2^20B
1GB=1024MB=2^30B
1TB=1024GB=2^40B
1PB=1024TB=2^50B
1EB=1024PB=2^60B
1ZB=1024EB=2^70B
1YB=1024ZB=2^80B
1BB=1024YB=2^90B
目前大数据级别的入门数据单位为存储单位的哪个级别
PB级

3.模式在数据库中指的是什么?

模式也称逻辑模式,是数据库中全体数据的逻辑结构和特征的描述,是所有用户的公共数据视图。

4.简述TRDB与NoSQL的主要技术特点区别。

TRDB:(1)使用强存储模式技术。
(2)采用SQL技术标准来定义和操作数据库
(3)采用强事务保证可用性及安全性
(4)主要采用单机集中式处理(CP,Centralized Processing)方式。
NoSQL:(1)使用弱存储模技术
(2)没有采用SQL技术标准来定义和操作数据库
(3)采用弱事务保证数据可用性及安全性或根本没有事务处理机制。
(4)主要采用多机分布式处理(DP,Distributed Processing)方式

5.简述NoSQL与NewSQL的主要区别。

NoSQL采取的是最终一致性原则,NewSQL选择汲取了SQL和NewSQL的优点,希望将ACID和可扩展性以及高性能结合,但是目前而言,不适用于所有的场景。

6.NoSQL技术诞生的最初出发点是为了解决什么问题?

1、解决传统关系型数据库无法解决的数据存储及访问问题。
2、要解决大数据应用问题。
3、要解决互联网上应用问题。
4、要解决处理速度的响应和海量数据的储存问题。

7.简述各种NoSQL数据库的共同特性?

NoSQL数据库所共同具备的特征:
1)NoSQL数据库不使用SQL;
2)它们通常都是开源项目;
3)大多数NoSQL数据库的研发动机,都是为了要在集群环境中运行;
4)操作NoSQL数据库不需要使用“模式”。

8.一个互联网在线电子商务网站,用到MongoDB、Redis、Oracle三种数据库,是否可行?请说明理由。

本质上是可以的,但是由于资金、耗时等因素,对于一些小型网站来说不必用Oracle这种大型的数据库。如果该网站储存量过于巨大,可以考虑将网站中每一个模块分别对应一个数据库进行分开储存。这样更加便于管理。但是大多数情况下还是推荐使用MOngoDB数据库,MongoDB 是一个面向文档存储的数据库,操作起来比较简单和容易。

9.现有流行的数据库可以分为TRDB、NoSQL、NewSQL三大类,网上不同数据类型的支持者,开始不断争论,都认为对方的技术有问题了,甚至会被淘汰。请你给出自己的观点。

我认为这三者会相辅相成,共同促进彼此的发展,TRDB无法解决大数据时代的数据存储及快速读写功能,而NoSQL可以很好的解决这个问题,但是NoSQL采取的是最终一致性原则,NewSQL选择汲取了SQL和NewSQL的优点,将ACID和可扩展性以及高性能结合,这样可以使我们的项目具有更高的性能及拓展性。

第二章

1.请写出TRDB与NoSQL软件实现技术的区别。

(1)数据库数据存储模式不一样,TRDB为强数据存储模式,NoSQL为弱数据存储模式
(2)分布式技术是NoSQL的核心技术思路,而TRDB以集中部署一台物理机为最初出发点
(3)TRDB的事务严格遵循ACID原则,而NoSQL主题遵循Base原则
(4)TRDB都遵循SQL操作标准,NoSQL没有统一的操作标准
(5)TRDB基于单机的硬盘数据处理技术为主,NoSQL基于分布式的或者内存处理技术为主
(6)NoSQL在数据库软件功能上遵循“由繁入简”的设计思想

2.举例阐述事务的ACID特性。

ACID特性数据库中的事务有四个特性,分别是:
1)原子性
一个事务中的所有操作,要么全部完成,要么全部不完成,不会结束在中间某个环节。事务在执行过程中发生错误,会被回滚到事务开始前的状态,就像这个事务从来没有执行过一样。
例如:在某业务中,要确保订单表和商品销售表的数据同步处理,要么都处理成功,要么都处理失败
2)一致性
事务的一致性指的是在一个事务执行之前和执行之后数据库都必须处于一致性状态。如果事务成功地完成,那么系统中所有变化将正确地应用,系统处于有效状态。如果在事务中出现错误,那么系统中的所有变化将自动地回滚,系统返回到原始状态。
例如:订单表里记录了新销售出去1本书,那么在商品销售表里应该减少一本书,他们的总数最终要保持操作前后一致状态
3)隔离性
指的是在并发环境中,当不同的事务同时操纵相同的数据时,每个事务都有各自的完整数据空间。由并发事务所做的修改必须与任何其他并发事务所做的修改隔离。事务查看数据更新时,数据所处的状态要么是另一事务修改它之前的状态,要么是另一事务修改它之后的状态,事务不会查看到中间状态的数据。
例如:在(2)例中,处理业务过程中,商品销售表里该书的数量被事务所定,要么展示给新购买者处理成功的数量(减少1本后),要么展示给处理不成功的数量(不改变)
4)持久性
指的是只要事务成功结束,它对数据库所做的更新就必须永久保存下来。即使发生系统崩溃,重新启动数据库系统后,数据库还能恢复到事务成功结束时的状态。
例如:在上述例子中,最后事务处理结果要在数据库记录上永久改变,如事务处理成功了,那么应该是减1后的记录

3.举例阐述CAP定理。

(1)一致性,指的是在同一时刻,任何一个终端客户在每个节点都能读到最新写入的数据;这里的核心要求至少两台服务器保存着一样的数据,一致性从客户角度是针对“读(选择)”。可以简单理解为同步数据复制功能。
(2)可用性,指的是一个运行的节点在合理的时间内总能响应更新请求,不会发生错误或超时;可用性从客户角度是针对“更新(插入、修改、删除)”,可以简单理解为满足随时更新操作功能
(3)分区容错性,指的是当网络发生故障时,系统仍能继续保持响应客户读请求的能力。可以简单理解为满足随时读有效数据功能
例如:假设,Slave1节点服务器、Slave2节点服务器,都存储一样的数据,如商品基本信息。其中Slave2若发生故障。
当一个客户继续提交新的商品信息时,若要保证一致性,那么就要拒绝该更新操作,会导致无法满足可用性;若要满足可用性,继续写入Slavel时,则无法满足一致性问题;当一个客户要读取信息时,若允许只能读取Slave1信息,满足了分区容错性和可用性,但是无法保证一致性。

4.举例阐述BASE原则。

(1)基本可用,NoSQL允许分布式系统中某些部分出现故障,那么系统的其余部分依然可以继续运作。它不会像ACID那样,在系统出现故障时,进行强制拒绝,允许继续部分访问。
(2)软状态,NoSQL在数据处理过程中,允许这个过程,存在数据状态暂时不一致的情况。但经过纠错处理,最终会一致的。
(3)最终一致性,NoSQL的软状态允许数据处理过程状态的暂时不一致,但是最终处理结果将是一致的。这句话告诉我们NoSQL对数据处理过程可以有短暂的时间间隔,也允许分更细的步骤一个一个地处理,最后数据达到一致性即可。
例如:在海量客户访问时,客户更加关心自己的订单能否塞入购物车(基本可用,至少订单能得到记录),而可以暂时忽略网上购物栏里显示的还有多少个商品。事实先做购买预存,比这个商品实际数量的一致性要重要得多。客户有了购物车里的预存记录,他(她)还可以继续浏览购物(存在软状态了,商品数量和订单数量与最终的总数量不一致了),直到最后结账(最终一致)。允许购物过程商品数量状态的暂时不一致,先保证客户的购买体验需要,这就是BASE想要达到的目的。

第三章

运行generate_words.js脚本。在words数据库中导入word_stats集合中的数据,文档结构如下。

var vowelArr = "aeiou";
var consenantArr = "bcdfghjklmnpqrstvwxyz";
var words = "the,be,and,of,a,in,to,have,to,it,I,that,for,you,he,with,on,do,don't,won't,can't,shouldn't,say,this,they,at,but,we,his,from,that,not,by,she,or,as,what,go,their,can,who,get,if,would,her,all,my,make,about,know,will,as,up,one,time,there,year,so,think,when,which,them,some,me,people,take,out,into,just,see,him,your,come,could,now,than,like,other,how,then,its,our,two,more,these,want,way,look,first,also,new,because,day,more,use,no,man,find,here,thing,give,many,well,only,those,tell,one,very,her,even,back,any,good,woman,through,us,life,child,there,work,down,may,after,should,call,world,over,school,still,try,in,as,last,ask,need,too,feel,three,when,state,never,become,between,high,really,something,most,another,much,family,own,out,leave,put,old,while,mean,on,keep,student,why,let,great,same,big,group,begin,seem,country,help,talk,where,turn,problem,every,start,hand,might,American,show,part,about,against,place,over,such,again,few,case,most,week,company,where,system,each,right,program,hear,so,question,during,work,play,government,run,small,number,off,always,move,like,night,live,Mr,point,believe,hold,today,bring,happen,next,without,before,large,all,million,must,home,under,water,room,write,mother,area,national,money,story,young,fact,month,different,lot,right,study,book,eye,job,word,though,business,issue,side,kind,four,head,far,black,long,both,little,house,yes,after,since,long,provide,service,around,friend,important,father,sit,away,until,power,hour,game,often,yet,line,political,end,among,ever,stand,bad,lose,however,member,pay,law,meet,car,city,almost,include,continue,set,later,community,much,name,five,once,white,least,president,learn,real,change,team,minute,best,several,idea,kid,body,information,nothing,ago,right,lead,social,understand,whether,back,watch,together,follow,around,parent,only,stop,face,anything,create,public,already,speak,others,read,level,allow,add,office,spend,door,health,person,art,sure,such,war,history,party,within,grow,result,open,change,morning,walk,reason,low,win,research,girl,guy,early,food,before,moment,himself,air,teacher,force,offer,enough,both,education,across,although,remember,foot,second,boy,maybe,toward,able,age,off,policy,everything,love,process,music,including,consider,appear,actually,buy,probably,human,wait,serve,market,die,send,expect,home,sense,build,stay,fall,oh,nation,plan,cut,college,interest,death,course,someone,experience,behind,reach,local,kill,six,remain,effect,use,yeah,suggest,class,control,raise,care,perhaps,little,late,hard,field,else,pass,former,sell,major,sometimes,require,along,development,themselves,report,role,better,economic,effort,up,decide,rate,strong,possible,heart,drug,show,leader,light,voice,wife,whole,police,mind,finally,pull,return,free,military,price,report,less,according,decision,explain,son,hope,even,develop,view,relationship,carry,town,road,drive,arm,true,federal,break,better,difference,thank,receive,value,international,building,action,full,model,join,season,society,because,tax,director,early,position,player,agree,especially,record,pick,wear,paper,special,space,ground,form,support,event,official,whose,matter,everyone,center,couple,site,end,project,hit,base,activity,star,table,need,court,produce,eat,American,teach,oil,half,situation,easy,cost,industry,figure,face,street,image,itself,phone,either,data,cover,quite,picture,clear,practice,piece,land,recent,describe,product,doctor,wall,patient,worker,news,test,movie,certain,north,love,personal,open,support,simply,third,technology,catch,step,baby,computer,type,attention,draw,film,Republican,tree,source,red,nearly,organization,choose,cause,hair,look,point,century,evidence,window,difficult,listen,soon,culture,billion,chance,brother,energy,period,course,summer,less,realize,hundred,available,plant,likely,opportunity,term,short,letter,condition,choice,place,single,rule,daughter,administration,south,husband,Congress,floor,campaign,material,population,well,call,economy,medical,hospital,church,close,thousand,risk,current,fire,future,wrong,involve,defense,anyone,increase,security,bank,myself,certainly,west,sport,board,seek,per,subject,officer,private,rest,behavior,deal,performance,fight,throw,top,quickly,past,goal,second,bed,order,author,fill,represent,focus,foreign,drop,plan,blood,upon,agency,push,nature,color,no,recently,store,reduce,sound,note,fine,before,near,movement,page,enter,share,than,common,poor,other,natural,race,concern,series,significant,similar,hot,language,each,usually,response,dead,rise,animal,factor,decade,article,shoot,east,save,seven,artist,away,scene,stock,career,despite,central,eight,thus,treatment,beyond,happy,exactly,protect,approach,lie,size,dog,fund,serious,occur,media,ready,sign,thought,list,individual,simple,quality,pressure,accept,answer,hard,resource,identify,left,meeting,determine,prepare,disease,whatever,success,argue,cup,particularly,amount,ability,staff,recognize,indicate,character,growth,loss,degree,wonder,attack,herself,region,television,box,TV,training,pretty,trade,deal,election,everybody,physical,lay,general,feeling,standard,bill,message,fail,outside,arrive,analysis,benefit,name,forward,lawyer,present,section,environmental,glass,answer,skill,sister,PM,professor,operation,financial,crime,stage,ok,compare,authority,miss,design,sort,one,act,ten,knowledge,gun,station,blue,state,strategy,little,clearly,discuss,indeed,force,truth,song,example,democratic,check,environment,leg,dark,public,various,rather,laugh,guess,executive,set,study,prove,hang,entire,rock,design,enough,forget,since,claim,note,remove,manager,help,close,sound,enjoy,network,legal,religious,cold,form,final,main,science,green,memory,card,above,seat,cell,establish,nice,trial,expert,that,spring,firm,Democrat,radio,visit,management,care,avoid,imagine,tonight,huge,ball,no,close,finish,yourself,talk,theory,impact,respond,statement,maintain,charge,popular,traditional,onto,reveal,direction,weapon,employee,cultural,contain,peace,head,control,base,pain,apply,play,measure,wide,shake,fly,interview,manage,chair,fish,particular,camera,structure,politics,perform,bit,weight,suddenly,discover,candidate,top,production,treat,trip,evening,affect,inside,conference,unit,best,style,adult,worry,range,mention,rather,far,deep,past,edge,individual,specific,writer,trouble,necessary,throughout,challenge,fear,shoulder,institution,middle,sea,dream,bar,beautiful,property,instead,improve,stuff,detail,method,sign,somebody,magazine,hotel,soldier,reflect,heavy,cause,bag,heat,fall,marriage,tough,sing,surface,purpose,exist,pattern,whom,skin,agent,owner,machine,gas,down,ahead,generation,commercial,address,cancer,test,item,reality,coach,step,Mrs,yard,beat,violence,total,tend,investment,discussion,finger,garden,notice,collection,modern,task,partner,positive,civil,kitchen,consumer,shot,budget,wish,painting,scientist,safe,agreement,capital,mouth,nor,victim,newspaper,instead,threat,responsibility,smile,attorney,score,account,interesting,break,audience,rich,dinner,figure,vote,western,relate,travel,debate,prevent,citizen,majority,none,front,born,admit,senior,assume,wind,key,professional,mission,fast,alone,customer,suffer,speech,successful,option,participant,southern,fresh,eventually,no,forest,video,global,Senate,reform,access,restaurant,judge,publish,cost,relation,like,release,own,bird,opinion,credit,critical,corner,concerned,recall,version,stare,safety,effective,neighborhood,original,act,troop,income,directly,hurt,species,immediately,track,basic,strike,hope,sky,freedom,absolutely,plane,nobody,achieve,object,attitude,labor,refer,concept,client,powerful,perfect,nine,therefore,conduct,announce,conversation,examine,touch,please,attend,completely,vote,variety,sleep,turn,involved,investigation,nuclear,researcher,press,conflict,spirit,experience,replace,British,encourage,lot,lot,lot,lot,argument,by,once,camp,brain,feature,afternoon,AM,weekend,dozen,possibility,along,insurance,department,battle,beginning,date,generally,very,sorry,crisis,complete,fan,stick,define,easily,through,hole,element,vision,status,normal,Chinese,ship,solution,stone,slowly,scale,bit,university,introduce,driver,attempt,park,spot,lack,ice,boat,drink,sun,front,distance,wood,handle,truck,return,mountain,survey,supposed,tradition,winter,village,Soviet,refuse,sales,roll,communication,run,screen,gain,resident,hide,gold,club,future,farm,potential,increase,middle,European,presence,independent,district,shape,reader,Ms,contract,crowd,Christian,express,apartment,willing,strength,previous,band,obviously,horse,interested,target,prison,ride,guard,terms,demand,reporter,deliver,text,share,tool,wild,vehicle,observe,flight,inside,facility,understanding,average,emerge,advantage,quick,light,leadership,earn,pound,basis,bright,operate,guest,sample,contribute,tiny,block,protection,settle,feed,collect,additional,while,highly,identity,title,mostly,lesson,faith,river,promote,living,present,count,unless,marry,tomorrow,technique,path,ear,shop,folk,order,principle,survive,lift,border,competition,jump,gather,limit,fit,claim,cry,equipment,worth,associate,critic,warm,aspect,result,insist,failure,annual,French,Christmas,comment,responsible,affair,approach,until,procedure,regular,spread,chairman,baseball,soft,ignore,egg,measure,belief,demonstrate,anybody,murder,gift,religion,review,editor,past,engage,coffee,document,speed,cross,influence,anyway,threaten,commit,female,youth,wave,move,afraid,quarter,background,native,broad,wonderful,deny,apparently,slightly,reaction,twice,suit,perspective,growing,blow,construction,kind,intelligence,destroy,cook,connection,charge,burn,shoe,view,grade,context,committee,hey,mistake,focus,smile,location,clothes,Indian,quiet,dress,promise,aware,neighbor,complete,drive,function,bone,active,extend,chief,average,combine,wine,below,cool,voter,mean,demand,learning,bus,hell,dangerous,remind,moral,United,category,relatively,victory,key,academic,visit,Internet,healthy,fire,negative,following,historical,medicine,tour,depend,photo,finding,grab,direct,classroom,contact,justice,participate,daily,fair,pair,famous,exercise,knee,flower,tape,hire,familiar,appropriate,supply,fully,cut,will,actor,birth,search,tie,democracy,eastern,primary,yesterday,circle,device,progress,next,front,bottom,island,exchange,clean,studio,train,lady,colleague,application,neck,lean,damage,plastic,tall,plate,hate,otherwise,writing,press,male,start,alive,expression,football,intend,attack,chicken,army,abuse,theater,shut,map,extra,session,danger,welcome,domestic,lots,literature,rain,desire,assessment,injury,respect,northern,nod,paint,fuel,leaf,direct,dry,Russian,instruction,fight,pool,climb,sweet,lead,engine,fourth,salt,expand,importance,metal,fat,ticket,software,disappear,corporate,strange,lip,reading,urban,mental,increasingly,lunch,educational,somewhere,farmer,above,sugar,planet,favorite,explore,obtain,enemy,greatest,complex,surround,athlete,invite,repeat,carefully,soul,scientific,impossible,panel,meaning,mom,married,alone,instrument,predict,weather,presidential,emotional,commitment,Supreme,bear,pocket,thin,temperature,surprise,poll,proposal,consequence,half,breath,sight,cover,balance,adopt,minority,straight,attempt,connect,works,teaching,belong,aid,advice,okay,photograph,empty,regional,trail,novel,code,somehow,organize,jury,breast,Iraqi,human,acknowledge,theme,storm,union,record,desk,fear,thanks,fruit,under,expensive,yellow,conclusion,prime,shadow,struggle,conclude,analyst,dance,limit,like,regulation,being,last,ring,largely,shift,revenue,mark,locate,county,appearance,package,difficulty,bridge,recommend,obvious,train,basically,e-mail,generate,anymore,propose,thinking,possibly,trend,visitor,loan,currently,comfortable,investor,but,profit,angry,crew,deep,accident,male,meal,hearing,traffic,muscle,notion,capture,prefer,truly,earth,Japanese,chest,search,thick,cash,museum,beauty,emergency,unique,feature,internal,ethnic,link,stress,content,select,root,nose,declare,outside,appreciate,actual,bottle,hardly,setting,launch,dress,file,sick,outcome,ad,defend,matter,judge,duty,sheet,ought,ensure,Catholic,extremely,extent,component,mix,long-term,slow,contrast,zone,wake,challenge,airport,chief,brown,standard,shirt,pilot,warn,ultimately,cat,contribution,capacity,ourselves,estate,guide,circumstance,snow,English,politician,steal,pursue,slip,percentage,meat,funny,neither,soil,influence,surgery,correct,Jewish,blame,estimate,due,basketball,late,golf,investigate,crazy,significantly,chain,address,branch,combination,just,frequently,governor,relief,user,dad,kick,part,manner,ancient,silence,rating,golden,motion,German,gender,solve,fee,landscape,used,bowl,equal,long,official,forth,frame,typical,except,conservative,eliminate,host,hall,trust,ocean,score,row,producer,afford,meanwhile,regime,division,confirm,fix,appeal,mirror,tooth,smart,length,entirely,rely,topic,complain,issue,variable,back,range,telephone,perception,attract,confidence,bedroom,secret,debt,rare,his,tank,nurse,coverage,opposition,aside,anywhere,bond,file,pleasure,master,era,requirement,check,stand,fun,expectation,wing,separate,now,clear,struggle,mean,somewhat,pour,stir,judgment,clean,except,beer,English,reference,tear,doubt,grant,seriously,account,minister,totally,hero,industrial,cloud,stretch,winner,volume,travel,seed,surprised,rest,fashion,pepper,separate,busy,intervention,copy,tip,below,cheap,aim,cite,welfare,vegetable,gray,dish,beach,improvement,everywhere,opening,overall,divide,initial,terrible,oppose,contemporary,route,multiple,essential,question,league,criminal,careful,core,upper,rush,necessarily,specifically,tired,rise,tie,employ,holiday,dance,vast,resolution,household,fewer,apart,witness,match,barely,sector,representative,lack,beneath,beside,black,incident,limited,proud,flow,faculty,increased,waste,merely,mass,emphasize,experiment,definitely,bomb,enormous,tone,liberal,massive,engineer,wheel,female,decline,invest,promise,cable,towards,expose,rural,AIDS,Jew,narrow,cream,secretary,gate,solid,hill,typically,noise,grass,unfortunately,hat,legislation,succeed,either,celebrate,achievement,fishing,drink,accuse,hand,useful,land,secret,reject,talent,taste,characteristic,milk,escape,cast,sentence,unusual,closely,convince,height,physician,assess,sleep,plenty,ride,virtually,first,addition,sharp,creative,lower,behind,approve,explanation,outside,gay,campus,proper,live,guilty,living,acquire,compete,technical,plus,mind,potential,immigrant,weak,illegal,hi,alternative,interaction,column,personality,signal,curriculum,list,honor,passenger,assistance,forever,fun,regard,Israeli,association,twenty,knock,review,wrap,lab,offer,display,criticism,asset,depression,spiritual,musical,journalist,prayer,suspect,scholar,warning,climate,cheese,observation,childhood,payment,sir,permit,cigarette,definition,priority,bread,creation,graduate,request,emotion,scream,dramatic,universe,gap,excellent,deeply,prosecutor,mark,green,lucky,drag,airline,library,agenda,recover,factory,selection,primarily,roof,unable,expense,initiative,diet,arrest,funding,therapy,wash,schedule,sad,brief,housing,post,purchase,existing,dark,steel,regarding,shout,remaining,visual,fairly,chip,violent,silent,suppose,self,bike,tea,perceive,comparison,settlement,layer,planning,far,description,later,slow,slide,widely,wedding,inform,portion,territory,immediate,opponent,abandon,link,mass,lake,transform,tension,display,leading,bother,consist,alcohol,enable,bend,saving,gain,desert,shall,error,release,cop,Arab,double,walk,sand,Spanish,rule,hit,print,preserve,passage,formal,transition,existence,album,participation,arrange,atmosphere,joint,reply,cycle,opposite,lock,whole,deserve,consistent,resistance,discovery,tear,exposure,pose,stream,sale,trust,benefit,pot,grand,mine,hello,coalition,tale,knife,resolve,racial,phase,present,joke,coat,Mexican,symptom,contact,manufacturer,philosophy,potato,interview,foundation,quote,online,pass,negotiation,good,urge,occasion,dust,breathe,elect,investigator,jacket,glad,ordinary,reduction,rarely,shift,pack,suicide,numerous,touch,substance,discipline,elsewhere,iron,practical,moreover,passion,volunteer,implement,essentially,gene,enforcement,vs,sauce,independence,marketing,priest,amazing,intense,advance,employer,shock,inspire,adjust,retire,sure,visible,kiss,illness,cap,habit,competitive,juice,congressional,involvement,dominate,previously,whenever,transfer,analyze,another,attach,for,Indian,disaster,parking,prospect,boss,complaint,championship,coach,exercise,fundamental,severe,enhance,mystery,impose,poverty,other,entry,fat,spending,king,evaluate,symbol,still,trade,maker,mood,accomplish,emphasis,illustrate,boot,monitor,Asian,entertainment,bean,evaluation,creature,commander,digital,arrangement,concentrate,total,usual,anger,psychological,heavily,peak,approximately,increasing,disorder,missile,equally,vary,wire,round,distribution,transportation,holy,ring,twin,command,commission,interpretation,breakfast,stop,strongly,engineering,luck,so-called,constant,race,clinic,veteran,smell,tablespoon,capable,nervous,tourist,light,toss,crucial,bury,pray,tomato,exception,butter,deficit,bathroom,objective,block,electronic,ally,journey,reputation,mixture,surely,tower,smoke,confront,pure,glance,dimension,toy,prisoner,fellow,smooth,nearby,peer,designer,personnel,shape,educator,relative,immigration,belt,teaspoon,birthday,implication,perfectly,coast,supporter,accompany,silver,teenager,recognition,retirement,flag,recovery,whisper,watch,gentleman,corn,moon,inner,junior,rather,throat,salary,swing,observer,due,straight,publication,pretty,crop,dig,strike,permanent,plant,phenomenon,anxiety,unlike,wet,literally,resist,convention,embrace,supply,assist,exhibition,construct,viewer,pan,consultant,soon,line,administrator,date,occasionally,mayor,consideration,CEO,secure,pink,smoke,estimate,buck,historic,poem,grandmother,bind,fifth,constantly,enterprise,favor,testing,stomach,apparent,weigh,install,sensitive,suggestion,mail,recipe,reasonable,preparation,wooden,elementary,concert,aggressive,false,intention,channel,extreme,tube,drawing,protein,quit,absence,roll,Latin,rapidly,jail,comment,diversity,honest,Palestinian,pace,employment,speaker,impression,essay,respondent,giant,cake,historian,negotiate,restore,substantial,pop,particular,specialist,origin,approval,mine,quietly,advise,conventional,drop,count,depth,wealth,disability,shell,general,criticize,fast,professional,effectively,biological,pack,onion,deputy,flat,brand,assure,mad,award,criteria,dealer,via,alternative,utility,precisely,arise,armed,nevertheless,highway,clinical,routine,schedule,wage,normally,phrase,ingredient,stake,Muslim,dream,fiber,activist,Islamic,snap,terrorism,refugee,incorporate,hip,ultimate,switch,corporation,valuable,assumption,gear,graduate,barrier,minor,provision,killer,assign,gang,developing,classic,chemical,wave,label,teen,index,vacation,advocate,draft,extraordinary,heaven,rough,yell,pregnant,distant,drama,satellite,personally,wonder,clock,chocolate,Italian,Canadian,ceiling,sweep,advertising,universal,spin,house,button,bell,rank,darkness,ahead,clothing,super,yield,fence,portrait,paint,survival,roughly,lawsuit,bottom,testimony,bunch,beat,wind,found,burden,react,chamber,furniture,cooperation,string,ceremony,communicate,taste,cheek,lost,profile,mechanism,disagree,like,penalty,match,ie,advance,resort,destruction,bear,unlikely,tissue,constitutional,pant,stranger,infection,cabinet,broken,apple,electric,proceed,track,bet,literary,virus,stupid,dispute,fortune,strategic,assistant,overcome,remarkable,occupy,statistics,shopping,cousin,encounter,wipe,initially,blind,white,port,honor,electricity,genetic,adviser,pay,spokesman,retain,latter,incentive,slave,chemical,translate,accurate,whereas,terror,though,expansion,elite,Olympic,dirt,odd,rice,bullet,tight,Bible,chart,solar,decline,conservative,process,square,stick,concentration,complicated,gently,champion,scenario,telescope,reflection,revolution,strip,interpret,friendly,tournament,fiction,detect,balance,likely,tremendous,lifetime,recommendation,flow,senator,market,hunting,salad,guarantee,innocent,boundary,pause,remote,satisfaction,journal,bench,lover,raw,awareness,surprising,withdraw,general,deck,similarly,newly,pole,testify,mode,dialogue,imply,naturally,mutual,founder,top,advanced,pride,dismiss,aircraft,delivery,mainly,bake,freeze,platform,finance,sink,attractive,respect,diverse,relevant,ideal,joy,worth,regularly,working,singer,evolve,shooting,partly,unknown,assistant,offense,counter,DNA,smell,potentially,transfer,thirty,justify,protest,crash,craft,treaty,terrorist,insight,possess,politically,tap,lie,extensive,episode,double,swim,tire,fault,loose,free,shortly,originally,considerable,prior,intellectual,mix,assault,relax,stair,adventure,external,proof,confident,headquarters,sudden,dirty,violation,tongue,license,hold,shelter,rub,controversy,entrance,favorite,practice,properly,fade,defensive,tragedy,net,characterize,funeral,profession,alter,spot,constitute,establishment,squeeze,imagination,target,mask,convert,comprehensive,prominent,presentation,regardless,easy,load,stable,introduction,appeal,pretend,not,elderly,representation,deer,split,violate,partnership,pollution,emission,steady,vital,neither,fate,earnings,oven,distinction,segment,nowhere,poet,mere,exciting,variation,comfort,radical,stress,adapt,Irish,honey,correspondent,pale,musician,significance,load,round,vessel,storage,flee,mm-hmm,leather,distribute,evolution,ill,tribe,shelf,can,grandfather,lawn,buyer,dining,wisdom,council,vulnerable,instance,garlic,capability,poetry,celebrity,gradually,stability,doubt,fantasy,scared,guide,plot,framework,gesture,depending,ongoing,psychology,since,counselor,witness,chapter,fellow,divorce,owe,pipe,athletic,slight,math,shade,tail,sustain,mount,obligation,angle,palm,differ,custom,store,economist,fifteen,soup,celebration,efficient,damage,composition,satisfy,pile,briefly,carbon,closer,consume,scheme,crack,frequency,tobacco,survivor,besides,in,psychologist,wealthy,galaxy,given,fund,ski,limitation,OK,trace,appointment,preference,meter,explosion,arrest,publicly,incredible,fighter,rapid,admission,hunter,educate,painful,friendship,aide,infant,calculate,fifty,rid,porch,tendency,uniform,formation,scholarship,reservation,efficiency,waste,qualify,mall,derive,scandal,PC,helpful,impress,heel,resemble,privacy,fabric,surprise,contest,proportion,guideline,rifle,maintenance,conviction,trick,organic,tent,examination,publisher,strengthen,French,proposed,myth,sophisticated,cow,etc,standing,asleep,tennis,nerve,barrel,bombing,membership,ratio,menu,purchase,controversial,desperate,rate,lifestyle,humor,loud,glove,suspect,sufficient,narrative,photographer,helicopter,Catholic,modest,provider,delay,agricultural,explode,stroke,scope,punishment,handful,badly,horizon,curious,downtown,girlfriend,prompt,request,cholesterol,absorb,adjustment,taxpayer,eager,principal,detailed,motivation,assignment,restriction,across,Palestinian,laboratory,workshop,differently,auto,romantic,cotton,motor,sue,flavor,overlook,float,undergo,sequence,demonstration,jet,orange,consumption,assert,blade,temporary,medication,print,cabin,bite,relative,edition,valley,yours,pitch,pine,brilliant,versus,manufacturing,risk,Christian,complex,absolute,chef,discrimination,offensive,German,suit,boom,register,appoint,heritage,God,terrorist,dominant,successfully,shit,lemon,hungry,sense,dry,wander,submit,economics,naked,anticipate,nut,legacy,extension,shrug,fly,battery,arrival,legitimate,orientation,inflation,cope,flame,cluster,host,wound,dependent,shower,institutional,depict,operating,flesh,garage,operator,instructor,collapse,borrow,furthermore,comedy,mortgage,sanction,civilian,twelve,weekly,habitat,grain,brush,consciousness,devote,crack,measurement,province,ease,seize,ethics,nomination,permission,wise,actress,summit,acid,odds,gifted,frustration,medium,function,physically,grant,distinguish,shore,repeatedly,lung,firm,running,correct,distinct,artistic,discourse,basket,ah,fighting,impressive,competitor,ugly,worried,portray,powder,ghost,persuade,moderate,subsequent,continued,cookie,carrier,cooking,frequent,ban,swing,orange,awful,admire,pet,miracle,exceed,rhythm,widespread,killing,lovely,sin,charity,script,tactic,identification,transformation,everyday,headline,crash,venture,invasion,military,nonetheless,adequate,piano,grocery,intensity,exhibit,high,blanket,margin,principal,quarterback,mouse,rope,concrete,prescription,chase,document,brick,recruit,patch,consensus,horror,recording,changing,painter,colonial,pie,sake,gaze,courage,pregnancy,swear,defeat,clue,reinforce,win,confusion,slice,occupation,dear,coal,sacred,criminal,formula,cognitive,collective,exact,uncle,square,captain,sigh,attribute,dare,okay,homeless,cool,gallery,soccer,defendant,tunnel,fitness,lap,grave,toe,container,virtue,abroad,architect,dramatically,makeup,inquiry,rose,surprisingly,highlight,decrease,indication,rail,anniversary,couch,alliance,hypothesis,boyfriend,compose,peer,mess,rank,legend,regulate,adolescent,shine,norm,upset,remark,resign,reward,gentle,related,organ,lightly,concerning,invent,laughter,fit,northwest,counseling,tight,receiver,ritual,insect,interrupt,salmon,favor,trading,concern,magic,superior,combat,stem,surgeon,acceptable,physics,rape,counsel,brush,jeans,hunt,continuous,log,echo,pill,excited,sculpture,compound,integrate,flour,bitter,bare,slope,rent,presidency,serving,subtle,greatly,bishop,drinking,delay,cry,acceptance,collapse,shop,pump,candy,evil,final,finance,pleased,medal,beg,sponsor,ethical,secondary,slam,export,experimental,melt,midnight,net,curve,integrity,entitle,evident,logic,essence,park,exclude,harsh,closet,suburban,greet,favor,interior,corridor,murder,retail,pitcher,march,snake,pitch,excuse,cross,weakness,pig,cold,classical,estimated,T-shirt,online,unemployment,civilization,fold,patient,pop,daily,reverse,missing,correlation,humanity,flash,developer,reliable,excitement,beef,Islam,Roman,stretch,architecture,occasional,administrative,elbow,deadly,Muslim,Hispanic,allegation,tip,confuse,airplane,monthly,duck,dose,Korean,plead,initiate,lecture,van,sixth,bay,mainstream,suburb,sandwich,unlike,trunk,rumor,implementation,swallow,motivate,render,longtime,trap,restrict,cloth,seemingly,legislative,effectiveness,enforce,lens,reach,inspector,lend,plain,fraud,companion,contend,nail,array,strict,assemble,frankly,rat,burst,hallway,cave,inevitable,southwest,monster,speed,protest,unexpected,obstacle,facilitate,encounter,rip,herb,overwhelming,integration,crystal,recession,wish,top,written,motive,label,flood,pen,ownership,nightmare,notice,inspection,supervisor,consult,arena,laugh,diagnosis,possession,forgive,warm,consistently,basement,project,drift,drain,last,prosecution,maximum,announcement,warrior,prediction,bacteria,questionnaire,mud,infrastructure,hurry,privilege,temple,medium,outdoor,suck,and/or,broadcast,re,leap,random,past,wrist,curtain,monitor,pond,domain,guilt,cattle,subject,walking,playoff,minimum,fiscal,skirt,dump,hence,database,uncomfortable,aim,execute,limb,ideology,average,welcome,tune,continuing,harm,railroad,endure,radiation,horn,chronic,peaceful,innovation,strain,guitar,replacement,behave,administer,simultaneously,dancer,amendment,guard,pad,transmission,await,retired,trigger,spill,grateful,grace,virtual,response,colony,adoption,slide,indigenous,closed,convict,civilian,towel,modify,particle,award,glance,prize,landing,conduct,blue,boost,bat,alarm,festival,grip,weird,undermine,freshman,sweat,outer,European,drunk,survey,research,separation,traditionally,stuff,govern,southeast,intelligent,wherever,ballot,rhetoric,convinced,driving,vitamin,enthusiasm,accommodate,praise,injure,wilderness,nearby,endless,mandate,pause,excuse,respectively,uncertainty,chaos,short,mechanical,canvas,forty,matter,lobby,profound,format,trait,currency,turkey,reserve,beam,abuse,astronomer,corruption,contractor,apologize,doctrine,genuine,thumb,unity,compromise,horrible,behavioral,exclusive,scatter,commonly,convey,rush,twist,complexity,fork,disk,relieve,suspicion,lock,finish,health-care,health-care,health-care,health-care,residence,shame,meaningful,sidewalk,Olympics,technological,signature,pleasant,wow,suspend,rebel,frozen,desire,spouse,fluid,pension,resume,theoretical,sodium,blow,promotion,delicate,forehead,rebuild,bounce,electrical,hook,detective,traveler,click,compensation,signal,exit,attraction,dedicate,altogether,pickup,carve,needle,belly,ship,scare,portfolio,shuttle,invisible,timing,engagement,ankle,transaction,rescue,counterpart,historically,firmly,mild,rider,doll,noon,exhibit,amid,identical,precise,anxious,structural,residential,loud,diagnose,carbohydrate,liberty,poster,theology,nonprofit,crawl,oxygen,handsome,magic,sum,provided,businessman,promising,conscious,determination,donor,hers,pastor,jazz,opera,Japanese,bite,frame,evil,acquisition,pit,hug,wildlife,punish,giant,primary,equity,wrong,doorway,departure,elevator,teenage,guidance,happiness,statue,pursuit,repair,decent,gym,oral,clerk,Israeli,envelope,reporting,destination,fist,endorse,exploration,generous,bath,rescue,thereby,overall,indicator,sunlight,feedback,spectrum,purple,laser,bold,reluctant,starting,expertise,practically,program,picture,tune,eating,age,volunteer,hint,sharply,parade,advocate,realm,ban,strip,cancel,blend,therapist,slice,peel,pizza,recipient,hesitate,flip,accounting,debate,bias,huh,metaphor,candle,handle,worry,judicial,entity,suffering,full-time,feel,lamp,garbage,servant,addition,regulatory,diplomatic,elegant,inside,reception,vanish,automatically,chin,trail,necessity,confess,racism,starter,interior,banking,casual,gravity,enroll,diminish,prevention,Arab,value,minimize,chop,performer,intent,isolate,pump,inventory,productive,assembly,civic,silk,magnitude,steep,hostage,collector,popularity,kiss,alien,dynamic,scary,equation,angel,switch,offering,rage,photography,repair,toilet,disappointed,precious,prohibit,representative,content,realistic,Russian,hidden,command,tender,wake,gathering,outstanding,stumble,lonely,automobile,artificial,dawn,abstract,descend,silly,hook,tide,shared,hopefully,readily,cooperate,revolutionary,romance,hardware,pillow,kit,cook,spread,continent,seal,circuit,sink,ruling,shortage,annually,lately,trap,scan,fool,deadline,rear,processing,ranch,coastal,undertake,softly,reserve,burning,verbal,tribal,ridiculous,automatic,diamond,credibility,import,spring,way,divine,sentiment,cart,oversee,stem,o'clock,elder,o'clock,o'clock,o'clock,pro,inspiration,Dutch,quantity,trailer,mate,o'clock,Greek,genius,monument,bid,quest,sacrifice,invitation,accuracy,juror,officially,broker,treasure,loyalty,credit,shock,talented,gasoline,stiff,output,nominee,extended,please,diabetes,slap,toxic,alleged,jaw,grief,mysterious,rocket,donate,inmate,tackle,dynamics,bow,ours,senior,dignity,carpet,parental,bubble,heat,buddy,barn,sword,flash,seventh,glory,tightly,protective,tuck,drum,faint,post,queen,dilemma,input,specialize,northeast,shallow,liability,sail,merchant,stadium,improved,bloody,defeat,associated,withdrawal,refrigerator,nest,near,thoroughly,lane,ancestor,condemn,steam,accent,escape,optimistic,unite,cage,equip,shrimp,homeland,exchange,rack,costume,wolf,courtroom,statute,cartoon,besides,productivity,grin,symbolic,seal,bug,bless,aunt,agriculture,rock,hostile,root,conceive,combined,instantly,hay,vaccine,bonus,collaboration,mixed,opposed,orbit,grasp,patience,spite,tropical,voting,patrol,willingness,position,revelation,rent,calm,jewelry,Cuban,haul,concede,trace,wagon,afterward,spectacular,ruin,sheer,prior,immune,reliability,ass,alongside,bush,exotic,fascinating,secure,clip,thigh,bull,drawer,regard,sheep,discourage,coordinator,ideological,runner,secular,intimate,empire,cab,divorce,exam,documentary,neutral,biology,flexible,progressive,web,conspiracy,catch,casualty,republic,execution,terrific,whale,functional,star,draft,instinct,teammate,aluminum,whoever,ministry,verdict,instruct,skull,self-esteem,ease,cooperative,manipulate,bee,practitioner,loop,edit,whip,puzzle,mushroom,subsidy,boil,tragic,mathematics,mechanic,jar,respect,earthquake,pork,creativity,safely,underlying,dessert,sympathy,fisherman,incredibly,isolation,sock,near,jump,eleven,entrepreneur,syndrome,bureau,seat,workplace,ambition,touchdown,utilize,breeze,costly,ambitious,Christianity,presumably,influential,translation,uncertain,dissolve,object,statistical,gut,metropolitan,rolling,aesthetic,spell,insert,booth,helmet,waist,expected,lion,accomplishment,royal,panic,cast,crush,actively,cliff,minimal,cord,fortunately,cocaine,illusion,anonymous,tolerate,appreciation,commissioner,harm,flexibility,instructional,scramble,casino,tumor,decorate,sort,charge,pulse,equivalent,fixed,experienced,donation,diary,sibling,irony,spoon,midst,alley,upset,interact,soap,cute,rival,short-term,punch,pin,hockey,passing,persist,supplier,known,momentum,purse,shed,liquid,icon,elephant,consequently,legislature,associate,franchise,correctly,mentally,foster,bicycle,encouraging,cheat,access,heal,fever,filter,rabbit,coin,exploit,accessible,organism,sensation,partially,stay,upstairs,dried,minimum,pro,conservation,shove,backyard,charter,stove,consent,comprise,reminder,alike,placement,dough,grandchild,dam,reportedly,well-known,surrounding,ecological,outfit,unprecedented,columnist,workout,preliminary,patent,shy,quote,trash,disabled,gross,damn,hormone,texture,counter,pencil,associate,frontier,spray,bet,disclose,custody,banker,beast,interfere,oak,case,eighth,notebook,outline,gaze,attendance,speculation,uncover,behalf,innovative,shark,reward,mill,installation,stimulate,tag,vertical,swimming,fleet,catalog,outsider,sacrifice,desperately,stance,compel,sensitivity,someday,instant,debut,proclaim,worldwide,hike,required,confrontation,colorful,ideal,constitution,trainer,Thanksgiving,scent,stack,eyebrow,sack,cease,inherit,tray,pioneer,organizational,textbook,uh,nasty,shrink,model,emerging,dot,wheat,fierce,envision,rational,kingdom,aisle,weaken,protocol,exclusively,vocal,marketplace,openly,unfair,terrain,deploy,risky,pasta,genre,distract,merit,planner,depressed,chunk,closest,discount,no,ladder,jungle,migration,breathing,invade,hurricane,retailer,classify,wound,coup,aid,ambassador,density,supportive,curiosity,skip,aggression,stimulus,journalism,robot,flood,dip,likewise,informal,Persian,feather,sphere,tighten,boast,pat,perceived,sole,publicity,major,unfold,joke,well-being,validity,ecosystem,strictly,partial,collar,weed,compliance,streak,supposedly,added,builder,glimpse,premise,specialty,deem,artifact,sneak,monkey,mentor,two-thirds,two-third's,listener,lightning,legally,sleeve,disappointment,disturb,rib,excessive,high-tech,debris,pile,rod,logical,liberal,ash,socially,parish,slavery,blank,commodity,cure,mineral,hunger,dying,developmental,faster,spare,halfway,cure,equality,cemetery,harassment,deliberately,fame,regret,striking,likelihood,carrot,atop,toll,rim,embarrassed,fucking,cling,isolated,blink,suspicious,wheelchair,squad,eligible,processor,plunge,this,sponsor,grin,color,demographic,rain,chill,refuge,steer,legislator,rally,programming,cheer,outlet,intact,vendor,thrive,peanut,chew,elaborate,intellectual,conception,auction,steak,comply,triumph,shareholder,comparable,transport,conscience,calculation,considerably,interval,scratch,awake,jurisdiction,inevitably,feminist,constraint,emotionally,expedition,allegedly,compromise,strain,similarity,butt,lid,dumb,bulk,sprinkle,mortality,philosophical,conversion,patron,municipal,any,liver,harmony,solely,tolerance,instant,goat,arm,blessing,banana,running,palace,formerly,peasant,neat,grandparent,lawmaker,supermarket,cruise,mobile,plain,part,calendar,widow,deposit,beard,brake,downtown,screening,impulse,forbid,fur,brutal,predator,poke,opt,voluntary,trouble,valid,forum,dancing,happily,soar,removal,autonomy,enact,round,thread,light,landmark,unhappy,offender,coming,privately,fraction,distinctive,tourism,threshold,calm,routinely,suite,remark,regulator,straw,theological,apart,exhaust,globe,fragile,objection,chemistry,old-fashioned,crowded,circle,blast,prevail,overnight,denial,rental,fantastic,fragment,level,screw,warmth,undergraduate,liquid,headache,policeman,yield,projection,battle,suitable,mention,graduation,drill,cruel,mansion,regard,grape,authorize,cottage,driveway,charm,loyal,clay,pound,balloon,invention,ego,fare,homework,disc,sofa,guarantee,availability,radar,frown,regain,leave,permit,sweater,rehabilitation,rubber,retreat,molecule,freely,favorable,steadily,veteran,integrated,ha,youngster,broadcast,premium,accountability,overwhelm,one-third,contemplate,update,spark,ironically,fatigue,beyond,speculate,marker,low,preach,bucket,bomb,blond,confession,provoke,marble,substantially,twist,defender,fish,explicit,transport,disturbing,surveillance,magnetic,technician,mutter,devastating,depart,arrow,trauma,neighboring,soak,ribbon,meantime,transmit,screen,harvest,consecutive,republican,coordinate,worldwide,within,spy,slot,riot,nutrient,citizenship,severely,sovereignty,ridge,brave,lighting,specify,contributor,frustrate,crowd,articulate,importantly,transit,dense,seminar,electronics,sunny,shorts,swell,accusation,soften,photograph,straighten,terribly,cue,sudden,bride,biography,hazard,compelling,seldom,tile,economically,honestly,troubled,bow,twentieth,balanced,foreigner,launch,convenience,delight,weave,timber,till,accurately,plea,bulb,copy,flying,sustainable,devil,bolt,cargo,spine,seller,skilled,managing,public,marine,dock,organized,fog,diplomat,boring,sometime,summary,missionary,epidemic,fatal,trim,warehouse,accelerate,butterfly,bronze,drown,inherent,praise,nationwide,spit,harvest,kneel,vacuum,selected,dictate,stereotype,sensor,laundry,manual,pistol,naval,plaintiff,immigrant,kid,middle-class',middle-class,apology,till";
var wordArr = words.split(",");
var wordObjArr = new Array();
for (var i=0; i

NOSQL数据库习题_第1张图片

执行如下查询语句。并将查询执行命令运行结果截图上传。

我的答案

1、(1)获取集合中长度为5的单词,输出单词及长度信息。

db.word_stats.find({size:5},{_id:0,word:1,size:1})

NOSQL数据库习题_第2张图片

2、(2)根据字段first查找以a、b、c打头的单词,输出单词信息。

db.word_stats.find({first:{$in:[/^a/,/^b/,/^c/]}})

NOSQL数据库习题_第3张图片

3、(3)查找数组字段letters包含12个字母的单词。

db.word_stats.find({letters:{$size:12}})

NOSQL数据库习题_第4张图片

4、(4)查找数据字段letters包含长于12个字母的单词。

db.word_stats.find({$where: "this.letters.length > 12"}).pretty()

NOSQL数据库习题_第5张图片

5、(5)查找包含全部5个元音字母的单词。

db.word_stats.find({word:{$regex:/aeiou/}},{})

NOSQL数据库习题_第6张图片

6、(6)查找集合中共包含多少个单词。

db.word_stats.find().count()

NOSQL数据库习题_第7张图片

7、(7)显示前三个单词信息。

db.word_stats.find().limit(3)

NOSQL数据库习题_第8张图片

8、(8)返回first字段为t的文档时,要排除字段_id、stats和charsets。

db.word_stats.find({first:"t"},{_id:0,stats:0,charsets:0})

NOSQL数据库习题_第9张图片

9、(9)获取集合中size(单词长度)的不同值。

db.word_stats.distinct("size",{ })

NOSQL数据库习题_第10张图片

10、(10)获取集合中以“q”字母打头的size(单词长度)的不同值。

db.word_stats.distinct("size",{first: "q"})

NOSQL数据库习题_第11张图片

11、(11)获取集合中以“u”字母结尾的单词的first(首字母)的不同值。

db.word_stats.distinct("first",{word:{$regex:/u$/}})

NOSQL数据库习题_第12张图片

12、(12)获取集合中没有出现过辅音字母的单词的last(尾字母)的不同值。

db.word_stats.distinct("last",{charsets:{$size:1},"charsets.type":"vowels"})

NOSQL数据库习题_第13张图片

13、(13)获取集合中size(单词长度)超过10个的单词 中元音字母出现数目个数的不同值。

db.word_stats.distinct("stats.vowels",{size:{$gt:10}})

NOSQL数据库习题_第14张图片

14、(14)将已“w”开头的单词升序显示,只显示单词信息。

db.word_stats.find({first:"w"},{word:1}).sort({_id:0,word:1})

NOSQL数据库习题_第15张图片

15、(15)将单词按最后一个字母升序显示,单词长度降序显示,只显示单词信息。

db.word_stats.find({},{word:1}).sort({size:-1,last:1})

NOSQL数据库习题_第16张图片

16、(16)显示以元音字符开头和结尾的单词的数量。

db.word_stats.find({first:{$in:[/^a/,/^e/,/^i/,/^o/,/^u/]},last:{$in:[/^a/,/^e/,/^i/,/^o/,/^u/]}},{word:1}).count()

NOSQL数据库习题_第17张图片

第四章

按要求完成下列操作,将对应题目的运行命令和结果以截图方式上传。

(1)在test数据库goodsbaseinf集合中批量加入下列数据。

{ item: “小学生教材”,name:“《小学一年级语文》”,price:12 },

{ item: “高中生教材”,name:“《高中一年级语文》”,price:20},

{ item: “外语教材”,name:“《英语全解》”,price:30}

(2)查询goodsbaseinf集合中的的所有文档。

(3)将goodsbaseinf集合中的文档全部添加字段,num值为50。

(4)将goodsbaseinf集合中item值为“外语教材”的price增加5。

(5)将goodsbaseinf集合中的item值为"高中生教材“文档增加数组字段city:BeiJing。

(6)将goodsbaseinf集合中的item值为"高中生教材“文档中字段city添加值“TaiYuan”,“XiAn”。

(7) 将goodsbaseinf集合中的item值为"高中生教材“对应的文档中数组字段city中包含的值“TaiYuan”删除 。

(8) 将goodsbaseinf集合中的"小学生教材"删除。

我的答案

1、

db.goodsbaseinf.insert(
  [
    {
      item: "小学生教材",
      name: "《小学一年级语文》",
      price: 12
    },
    {
      item: "高中生教材",
      name: "《高中一年级语文》",
      price: 20
    },
    {
      item: "外语教材",
      name: "《英语全解》",
      price: 30
    }
  ]
)

NOSQL数据库习题_第18张图片

NOSQL数据库习题_第19张图片

2、

db.goodsbaseinf.find()

NOSQL数据库习题_第20张图片

3、

db.goodsbaseinf.update(
  {},
  {
    $set: {
      num: 50
    }
  },
  false,
  true
)

NOSQL数据库习题_第21张图片

NOSQL数据库习题_第22张图片

4、

db.goodsbaseinf.update(
  {
    item: "外语教材"
  },
  {
    $inc: {
      price: 5
    }
  },
  {
    multi: true
  }
)

NOSQL数据库习题_第23张图片

NOSQL数据库习题_第24张图片

5、

db.goodsbaseinf.update(
  {
    item: "高中生教材"
  },
  {
    $push: {
      city: "BeiJing"
    }
  },
  {
    multi: true
  }
)

NOSQL数据库习题_第25张图片

NOSQL数据库习题_第26张图片

6、

db.goodsbaseinf.update(
  {
    item: "高中生教材"
  },
  {
    $addToSet: {
      city: {
        $each: ["TaiYuan", "XiAn"]
      }
    }
  },
  {
    multi: true
  }
)

NOSQL数据库习题_第27张图片

NOSQL数据库习题_第28张图片

7、

db.goodsbaseinf.update(
  {
    item: "高中生教材"
  },
  {
    $pull: {
      city: "TaiYuan"
    }
  },
  {
    multi: true
  }
)

NOSQL数据库习题_第29张图片

NOSQL数据库习题_第30张图片

8、

db.goodsbaseinf.deleteMany({
  item: "小学生教材"
})

NOSQL数据库习题_第31张图片

NOSQL数据库习题_第32张图片

第五章

1.导入persons集合数据,将查询命令及命令运行结果截图上传。

1)查询出persons文档中前5条数据,只显示姓名。

2)查询出persons文档中5~10条的数据,只显示姓名。

3)按照年龄降序显示用户姓名、年龄数据。

4)查询persons中美国学生的人数。

5)查询出persons中一共有多少个国家分别是什么。

6) 查询persons中每个国家学生数学成绩最好的学生信息(必须在90以上)。

我的答案

1)db.persons.find({},{_id:0,name:1}).limit(5)

NOSQL数据库习题_第33张图片

2)db.persons.find({},{_id:0,name:1}).limit(5).skip(5)

NOSQL数据库习题_第34张图片

3)db.persons.find({},{_id:0,name:1,age:1}).sort({age:1}) 

在这里插入图片描述

4)db.persons.find({country:"USA"}).count()

NOSQL数据库习题_第35张图片

(5)db.persons.distinct("country",{ })
5)db.runCommand({distinct:"persons“ , key:"country"}).values

NOSQL数据库习题_第36张图片

(6)db.runCommand({group:{
ns:"persons",
key:{"country":true},
initial:{m:0},
$reduce:function(doc,prev){
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}
},
condition:{m:{$gt:90}}
}})



6)db.persons.group(
{
initial:{m:0},
condition:{m:{$gt:90}},
key:{"country":true},
$reduce:function(doc,prev){
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}}
}) 

NOSQL数据库习题_第37张图片

1)在goodsdb数据库,goods集合中录入以下数据集
{o_id:“A”,value:50,type:“X”}
{o_id:“A”,value:75,type:“X”}
{o_id:“B”,value:80,type:“X”}
{o_id:“C”,value:45,type:“Y”}

2)查询goods集合中的所有信息。
3)使用聚合操作方法aggregate完成查询统计功能:type类型为"X",按 o_id分组统计总value值。显示字段

名称为_id和total。

将查询命令及命令运行结果截图上传。

我的答案

1)use goodsdb
db.goods.insert([{o_id:"A",value:50,type:"X"},
{o_id:"A",value:75,type:"X"},
{o_id:"B",value:80,type:"X"},
{o_id:"C",value:45,type:"Y"}]) 

NOSQL数据库习题_第38张图片

(2)db.goods.find()

NOSQL数据库习题_第39张图片

(3) db.goods.aggregate([{ $match: { type: { $in: ["X"] } } }, { $group: { _id: '$o_id', total: { $sum: '$value' } } }])

3)db.goods.aggregate({$match:{type:"X"}},{$group:{_id:"$o_id",total:{$sum:"$value"}}})

NOSQL数据库习题_第40张图片

3.运行命令及结果截图上传。

1)test数据库emp集合中录入以下数据集
{location:“XiAn”,age:20,name:“zs”,goods_amount:10}
{location:“BeiJing”,age:21,name:“lisi”,goods_amount:20}
{location:“BeiJing”,age:22,name:“wangwu”,goods_amount:15}
{location:“XiAn”,age:23,name:“zhaoran”,goods_amount:21}
{location:“Taiyuan”,age:25,name:“wanglin”,goods_amount:43}
{location:“shanghai”,age:25,name:“liuyun”,goods_amount:18}

2)查询emp集合中的所有信息。

3)统计不同城市的员工人数总和,将统计结果输出到empcount集合中,查询显示结果。

4)统计不同城市的员工的goods_amount的总和,将统计结果输出到empinfo集合中,查询显示结果。

5)统计不同城市的人名列表,将统计结果输出到empinfo1集合中,查询显示结果。

6)统计不同城市年龄在25岁(不包括25岁)以下的人名列表,将统计结果输出到empinfo2集合中,查询显示结果。

我的答案

1)use test

db.emp.insert([{location:"XiAn",age:20,name:"zs",goods_amount:10},
{location:"BeiJing",age:21,name:"lisi",,goods_amount:20},
{location:"BeiJing",age:22,name:"wangwu",goods_amount:15},
{location:"XiAn",age:23,name:"zhaoran",goods_amount:21},
{location:"Taiyuan",age:25,name:"wanglin",goods_amount:43},
{location:"shanghai",age:25,name:"liuyun",goods_amount:18}])

NOSQL数据库习题_第41张图片

(2)db.emp.find()

NOSQL数据库习题_第42张图片

(3)var map = function(){ emit(this.location, 1); }
var reduce = function( key, values ){ return Array.sum(values); }
var options = { out: "empcount" }
db.emp.mapReduce( map, reduce, options )

db.empcount.find()



3)

>var map = function(){ emit(this.location,1); }
>var reduce = function( key, values ){ return Array.sum(values); }
>var options = { out: "empcount" }

>db.emp.mapReduce( map, reduce, options )

>db.empcount.find()

NOSQL数据库习题_第43张图片

(4)var map = function(){ emit(this.location,this.goods_amount); }
var reduce = function( key, values ){ return Array.sum(values); }
var options = { out: "empinfo" }
db.emp.mapReduce( map, reduce, options )

db.empinfo.find()



4)

>var map = function(){ emit(this.location,goods_amount); }
>var reduce = function( key, values ){ return Array.sum(values); }
>var options = { out: "empinfo" }

>db.emp.mapReduce( map, reduce, options )

>db.empinfo.find()

NOSQL数据库习题_第44张图片

(5)var map = function(){ emit(this.location, this.name); }
var reduce = function( key, values ){ return values.join(', '); }
var options = { out: "empinfo1" }
db.emp.mapReduce( map, reduce, options )

db.empinfo1.find()




5)

>var map = function(){ emit(this.location, this.name); }
>var reduce = function( key, values ){ return values.join(', '); }
>var options = { out: "empinfo1" }

>db.emp.mapReduce( map, reduce, options )

>db.empinfo1.find()

NOSQL数据库习题_第45张图片

(6)var map = function(){ emit(this.location, this.name); }
var reduce = function( key, values ){ return key + ': ' + values.join(','); }
var options = { query: { age: {$lt: 25} }, out: "empinfo2" }
db.emp.mapReduce( map, reduce, options )

db.empinfo2.find()





6)

>var map = function(){ emit(this.location, this.name); }
>var reduce = function( key, values ){ return key + ': ' + values.join(', '); }

>var options = { query: { age: {$lt: 25} }, out: "empinfo2" }
>db.mythings.mapReduce( map, reduce, options )

>db.empinfo2.find()

NOSQL数据库习题_第46张图片

NoSQL数据库上机测试

一、 操作题:(请将每小题命令执行过程及运行结果截图,否则不计分)

1) 新建xsgl数据库,在集合member中批量添加如下数据:

{sno:“1813001”,sname:“zs”,age:18,major:“通信工程”, course:[“matlab”]},

{sno:“1813002”,sname:“lisi”,age:23,major:“计算机科学与技术”, course:[“C”,“Java”]},

{sno:“1813003”,sname:“wangwu”,age:21,major:“软件工程”,course:[“C”,“python”]},

{sno:“1813004”,sname:“zs”,age:19,major:“软件工程”,course:[“C”]},

{sno:“1813005”,sname:“zhaoyun”,age:19,major:“网络工程”}

,将数据存储到xsgl数据库。完成上述操作后显示xsgl数据库中集合名称列表。

2) 查询member集合中的所有数据。(注意:显示结果显示所有字段信息,不包括_id字段。)

3) 查询年龄大于等于19岁且小于等于21岁的学生信息,查询结果要求显示学号,姓名,年龄。

4) 查询专业方向为“计算机科学与技术”或“网络工程”的学生信息, 查询结果要求显示学号,姓名,专业方向。

5) 查询member集合中共有多少个不同的专业方向,且输出专业方向列表。

6) 统计member集合中的学生人数。

7) 查询course属性列表中第二门课程是python的学生信息,查询结果要求显示_id,姓名。

8) 查询member集合中的所有文档,将查询结果按年龄降序排序,查询结果要求显示_id,姓名,年龄。

9) 更新或插入操作,查询member集合中是否存在姓名为“zhouyang”的学生,若不存在,增加该学生信息{sno:“1813007”,sname:" zhouyang ",age:18,major:“网络工程”},该操作完成后显示集合中全部数据。(注意:显示结果显示所有字段信息,不包括_id字段。)

10) 将所有major为“软件工程”的所有学生添加字段location,值为“loc01”。该操作完成后显示集合中全部数据。(注意:显示结果显示所有字段信息,包括_id字段。)

11) 将sno为"1813003"的学生选修课程中增加"JSP"课程。该操作完成后显示集合中全部数据。(注意:显示结果显示所有字段信息,包括_id字段。)

12) 删除major为“通信工程”的学生,删除后查看member集合中所有文档信息。(注意:显示结果显示所有学号,姓名,专业信息。)

13)使用MapReduce方法显示不同专业的人名列表(用“>>”号分割)。将查询结果输出到stu1集合中, 显示stu1集合的内容。

14)使用aggregate命令统计不同专业的学生的最大年龄(年龄在18岁以上,包括18岁),结果显示 major_name和age_max字段信息。

 我的答案
1、db.member.insert([{sno:"1813001",sname:"zs",age:18,major:"通信工程", course:["matlab"]},
{sno:"1813002",sname:"lisi",age:23,major:"计算机科学与技术", course:["C","Java"]},
{sno:"1813003",sname:"wangwu",age:21,major:"软件工程",course:["C","python"]},
{sno:"1813004",sname:"zs",age:19,major:"软件工程",course:["C"]},
{sno:"1813005",sname:"zhaoyun",age:19,major:"网络工程"}])

NOSQL数据库习题_第47张图片

2、db.member.find({},{_id:0})

NOSQL数据库习题_第48张图片

3、db.member.find({age:{$gte:19,$lte:21}},{_id:0,sno:1,sname:1,age:1})

NOSQL数据库习题_第49张图片

4、db.member.find({major:{$in:["计算机科学与技术","网络工程"]}},{_id:0,sno:1,sname:1,major:1})

NOSQL数据库习题_第50张图片

5、db.runCommand({distinct:"member",key:"major"}).values

NOSQL数据库习题_第51张图片

6、db.member.find().count();

NOSQL数据库习题_第52张图片

7、db.member.find({"course.1":"python"},{sname:1})

NOSQL数据库习题_第53张图片

8、db.member.find({},{sname:1,age:1}).sort({age:-1})

NOSQL数据库习题_第54张图片

9、db.member.update({"sname":"zhouyang"},{$setOnInsert:{sno:"1813007",sname:"zhouyang",age:18,major:"网络工程"}},{upsert:true})
db.member.find({},{_id:0})

NOSQL数据库习题_第55张图片

10、db.member.update({},{$set:{location:"loc01"}},false, true)
db.member.find()

NOSQL数据库习题_第56张图片

11、db.member.update({sno:"1813003"},{$push:{"course":"JSP"}})
db.member.find()

NOSQL数据库习题_第57张图片

12、db.member.remove({"major":"通信工程"})
db.member.find({},{_id:0,sno:1,sname:1,major:1})

NOSQL数据库习题_第58张图片

13、var map = function(){ emit(this.major, this.sname); } 
var reduce = function( key, values ){ return values.join('>>'); } 
var options = { out: "stu1" } 
db.member.mapReduce( map, reduce, options ) 
db.stu1.find()

NOSQL数据库习题_第59张图片

14、db.member.aggregate([{$group:{_id:"$major",age:{$max:"$age"}}},{$project:   
 {
  major_name:"$_id",                     
  age_max:"$age",      
  _id:0}                    
 }
])

NOSQL数据库习题_第60张图片

二、操作题:以下代码实现Java应用程序连接MongoDB服务器,访问自定义数据库”words”中所包含的” word_stats”集合中的数据,请根据注释补充完整代码,然后将程序在Eclipse或其他开发环境中运行,且将控制台输出的运行结果截图。

【数据准备:新建words数据库,运行generate_words.js脚本。在words数据库中导入word_stats集合中的数据,文档结构如下。
NOSQL数据库习题_第61张图片

public class JavaConnect {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
       //建立连接
      MongoClient mg=         (1)                  ;
       //访问words数据库
      MongoDatabase db=       (2)               ; 
      MongoCollection collection=         (3)                    ;//访问word_stats集合
      //访问word_stats集合中前10条数据
      FindIterable findIter=         (4)                   ; 
       //利用过滤器返回游标对象
 MongoCursor cur=        (5)         ;
//输出集合中共有多少个文档
       System.out.println("该单词库中共有:"+           (6)                 +"个单词。");
       System.out.println("前10个单词列表:");  
       //利用游标循环输出前10个文档的的"word"字段
       while(        (7)            ) {
           Document doc=      (8)              ; 
            System.out.println(      (9)              );
       }
       mg.close();        
   }
}

注:请将运行结果截图上传 第10空中。
我的答案
1、new  MongoClient("127.0.0.1:27017")
2、mg.getDatabase("words")
3、db.getCollection("word_stats")
4、collection.find().limit(10)
5、findIter.iterator()
6、collection.countDocuments()
7、cur.hasNext()
8、cur.next()
9、doc.get("word")
10、

NOSQL数据库习题_第62张图片

你可能感兴趣的:(习题集,nosql,数据库,mongodb)