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

在这里插入图片描述

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

我的答案

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

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

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

db.word_stats.find().count()

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

第四章

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

(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
    }
  ]
)

在这里插入图片描述

2、

db.goodsbaseinf.find()

在这里插入图片描述

3、

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

在这里插入图片描述

在这里插入图片描述

4、

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

在这里插入图片描述

在这里插入图片描述

5、

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

在这里插入图片描述

在这里插入图片描述

6、

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

在这里插入图片描述

在这里插入图片描述

7、

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

在这里插入图片描述

在这里插入图片描述

8、

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

在这里插入图片描述

在这里插入图片描述

第五章

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

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

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

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

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

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

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

我的答案

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

(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}},prev){
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}}
}) 

在这里插入图片描述

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",type:"X"},{o_id:"A",{o_id:"B",{o_id:"C",type:"Y"}]) 

(2)db.goods.find()

在这里插入图片描述

(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"}}})

在这里插入图片描述

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”,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",name:"zs",goods_amount:10},{location:"BeiJing",name:"lisi",goods_amount:20},name:"wangwu",goods_amount:15},{location:"XiAn",name:"zhaoran",goods_amount:21},{location:"Taiyuan",name:"wanglin",goods_amount:43},{location:"shanghai",name:"liuyun",goods_amount:18}])

在这里插入图片描述

(2)db.emp.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,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,options )

>db.empcount.find()

在这里插入图片描述

(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,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,options )

>db.empinfo.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,options )

db.empinfo1.find()




5)

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

>db.emp.mapReduce( map,options )

>db.empinfo1.find()

在这里插入图片描述

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

db.empinfo2.find()





6)

>var map = function(){ emit(this.location,'); }

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

>db.empinfo2.find()

在这里插入图片描述

NoSQL数据库上机测试

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

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

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

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

{sno:“1813003”,sname:“wangwu”,major:“软件工程”,“python”]},

{sno:“1813004”,age:19,course:[“C”]},

{sno:“1813005”,sname:“zhaoyun”,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 ",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",major:"通信工程",course:["matlab"]},{sno:"1813002",sname:"lisi",major:"计算机科学与技术",course:["C","Java"]},{sno:"1813003",sname:"wangwu",major:"软件工程","python"]},{sno:"1813004",course:["C"]},{sno:"1813005",sname:"zhaoyun",major:"网络工程"}])

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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,options ) 
db.stu1.find()

在这里插入图片描述

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

在这里插入图片描述

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

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

在这里插入图片描述

public class JavaConnect {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
       //建立连接
      MongoClient mg=         (1)                  ;
       //访问words数据库
      MongoDatabase db=       (2)               ; 
      MongoCollection<Document> collection=         (3)                    ;//访问word_stats集合
      //访问word_stats集合中前10条数据
      FindIterable<Document> findIter=         (4)                   ; 
       //利用过滤器返回游标对象
 MongoCursor<Document> 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、

在这里插入图片描述

原文地址:https://blog.csdn.net/cai_4/article/details/128582989

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读752次。关系型数据库关系型数据库是一个结构化的数据库,创建在关系模型(二维表模型)基础上,一般面向于记录SQL语句(标准数据查询语言)就是一种基于关系型数据库的语言,用于执行对关系型数据库中数据的检索和操作主流的关系数据库包括Oracle、Mysql、SQL Server、Microsoft Access、DB2等非关系型数据库NoSQL(nOSQL=Not Only SQL),意思是“不仅仅是SQL”,是非关系型数据库的总称。除了主流的关系型数据库外的数据库,都认为是非关系型主流的NoSQ.._redis是非关系型数据库吗
文章浏览阅读687次,点赞2次,收藏5次。商城系统中,抢购和秒杀是很常见的营销场景,在一定时间内有大量的用户访问商场下单,主要需要解决的问题有两个:1. 高并发对数据库产生的压力;2. 竞争状态下如何解决商品库存超卖;高并发对数据库产生的压力对于第一个问题,使用缓存来处理,避免直接操作数据库,例如使用 Redis。竞争状态下如何解决商品库存超卖对于第二个问题,需要重点说明。常规写法:查询出对应商品的库存,判断库存数量否大于 0,然后执行生成订单等操作,但是在判断库存是否大于 0 处,如果在高并发下就会有问题,导致库存_php库存结余并发
文章浏览阅读1.4k次。MongoTemplate开发spring-data-mongodb提供了MongoTemplate和MongoRepository两种方式访问MongoDB,MongoRepository的方式访问较为简单,MongoTemplate方式较为灵活,这两种方式在Java对于MongoDB的运用中相辅相成。_springboot插入指定的mongodb数据库
文章浏览阅读887次,点赞10次,收藏19次。1.背景介绍1. 背景介绍NoSQL数据库是一种非关系型数据库,它的特点是可以存储非结构化的数据,并且可以处理大量的数据。HBase是一个分布式、可扩展的列式存储系统,它是基于Google的Bigtable设计的。HBase是一个开源的NoSQL数据库,它的核心功能是提供高性能的随机读写访问。在本文中,我们将对比HBase与其他NoSQL数据库,例如Redis、MongoDB、Cass...
文章浏览阅读819次。MongoDB连接失败记录_edentialmechanisn-scram-sha-1
文章浏览阅读470次。mongodb抽取数据到ES,使用ELK内部插件无法获取数据,只能试试monstache抽取mongodb数据,但是monstache需要mongodb replica set 模式才能采集数据。############monstache-compose文件。#replicas set 启动服务。# 默认备份节点不能读写,可以设置。# mydb指的是需要同步的数据库。#登录主mongodb初始化rs。#primary 创建用户。# ip地址注意要修改。# ip地址注意要修改。_monstache csdn
文章浏览阅读913次,点赞4次,收藏5次。storage:fork: trueadmin登录切换数据库注意: use 代表创建并使用,当库中没有数据时默认不显示这个库删除数据库查看表清单> show tables # 或者 > show collections表创建db.createCollection('集合名称', [options])table1字段类型描述capped布尔(可选)如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。_mongodb5
文章浏览阅读862次。Centos7.9设置MongoDB开机自启(超全教程,一条龙)_mongodb centos开机启动脚本
文章浏览阅读1.3k次,点赞6次,收藏21次。NoSQL数据库使用场景以及架构介绍
文章浏览阅读856次,点赞21次,收藏20次。1.背景介绍1. 背景介绍NoSQL数据库是一种非关系型数据库,它的设计目标是为了解决传统关系型数据库(如MySQL、Oracle等)在处理大量不结构化数据方面的不足。NoSQL数据库可以处理大量数据,具有高性能、高可扩展性和高可用性。但是,与关系型数据库不同,NoSQL数据库没有固定的模式,数据结构也不一定是表格。在NoSQL数据库中,数据存储和查询都是基于键值对、列族、图形等不同的...
文章浏览阅读416次。NoSQL定义:非关系型、分布式、开放源码和具有横向扩展能力的下一代数据库。由c++编写的开源、高性能、无模式的基于分布式文件存储的文档型数据库特点:高性能、高可用性、高扩展性、丰富的查询支持、可替换已完场文档某个指定的数据字段应用场景:社交场景:使用mongodb存储用户信息游戏场景:用户信息,装备积分物流场景:订单信息,订单状态场景操作特点:数据量大;读写操作频繁;价值较低的数据,对事物性要求不高开源、c语言编写、默认端口号6379、key-value形式存在,存储非结构化数据。_nosql
文章浏览阅读1.5k次,点赞3次,收藏2次。Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Failed to create socket. at redis.clients.jedis.DefaultJedisSocketFactory.createSocket(DefaultJedisSocketFactory.java:110) at redis.clients.jedis.Connection.connect(Conne_redis.clients.jedis.exceptions.jedisconnectionexception: failed to create so
文章浏览阅读6.5k次,点赞3次,收藏12次。readAnyDatabase(在所有数据库上都有读取数据的权限)、readWriteAnyDatabase(在所有数据库上都有读写数据的权限)、userAdminAnyDatabase(在所有数据库上都有管理user的权限)、dbAdminAnyDatabase(管理所有数据库的权限);:clusterAdmin(管理机器的最高权限)、clusterManager(管理和监控集群的权限)、clusterMonitor(监控集群的权限)、hostManager( 管理Server);_mongodb创建用户密码并授权
文章浏览阅读593次。Redis是一个基于内存的键值型NoSQL数据库,在实际生产中有着非常广泛的用处_搭建本地redis
文章浏览阅读919次。Key 的最佳实践[业务名]:[数据名]:[id]足够简短:不超过 44 字节不包含特殊字符Value 的最佳实践:合理的拆分数据,拒绝 BigKey选择合适数据结构Hash 结构的 entry 数量不要超过 1000(默认是 500,如果达到上限则底层会使用哈希表而不是 ZipList,内存占用较多)设置合理的超时时间批量处理的方案:原生的 M 操作Pipeline 批处理注意事项:批处理时不建议一次携带太多命令。Pipeline 的多个命令之间不具备原子性。_redis高级实战
文章浏览阅读1.2k次。MongoDB 递归查询_mongodb数据库 递归
文章浏览阅读1.2k次。通过实际代码例子介绍:如何通过MongoTemplate和MongoRepository操作数据库数据_springboot操作mongodb
文章浏览阅读687次,点赞7次,收藏2次。首先欢迎大家阅读此文档,本文档主要分为三个模块分别是:Redis的介绍及安装、RedisDesktopManager可视化工具的安装、主从(哨兵)模式的配置。_redis 主从配置工具
文章浏览阅读764次。天下武功,无坚不摧,唯快不破!我的名字叫 Redis,全称是 Remote Dictionary Server。有人说,组 CP,除了要了解她外,还要给机会让她了解你。那么,作为开发工程师的你,是否愿意认真阅读此心法抓住机会来了解我,运用到你的系统中提升性能。我遵守 BSD 协议,由意大利人 Salvatore Sanfilippo 使用 C 语言编写的一个基于内存实现的键值型非关系(NoSQL)..._redis 7.2 源码
文章浏览阅读2k次。MongoDB 的增删改查【1】_mongodb $inc