MongoDB学习笔记(四)——MongoDB基础定义

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33206732/article/details/79917848

该篇博文是我在写后面的博文时,发现里面有很多MongoDB的基础的东西,如果大家不了解这些定义,可能会很迷惑,不知道说的什么,所以把该篇博文提前到第四篇,以便后面大家能够能够对后面的几篇博文有清晰的认识。

连接(Connection)、数据库(Database)、集合(Collection)、文档(Document)是MongoDB的重要的基础组件,了解这些组件能够帮助大家对MongoDB的存储数据有更清晰的认识,如果大家数据Mysql、orcale等关系型数据库的话。理解这些东西非常简单,只需要把一些观念转变一下即可。

连接(Connection)

顾名思义,连接对象能让我们访问MongoDB服务器,它表示到服务器的连接,让我们能够获取首选项。

要创建Connection对象,我们可以在MongoDB shell中使用Mongo(host:port),,或者在JavaScript文件中使用var con = new Mongo(host:port),或者使用connect(url, user, password)方法,该方法等同于Mongo().getDB();

当然其他的Connection对象的方法,大家可以参考后面的博文:MongoDB学习笔记(七)——MongoDB shell方法汇总,内部有我总结出3.6版本最新的MongoDB shell的所有方法。

文档(Document)

文档MongoDB的核心,其是MongoDB存放数据的最最基本的一个单位,每一个文档存放了MongoDB的一条数据。我们可以对比下关系型数据库中的,其概念虽然不一致,但是其作用是一致的,都是表示一条数据,只不过关系型数据库中的一条数据是放在一张表中的一行,而MongoDB的一条数据则是一个集合中的一个文档。

MongoDB的存放数据是以BSON格式存储到文档中的,也就是说,每一个文档都是一条BSON数据,例如:{“name”:”test”,”age”:18}.其内部有两个键name、age,其值分别为test、18.

文档中的键值对的是有顺序的,比如{“age”:18,”name”:”test”}和上一条是两条数据,而不是同一条。

文档中每个键对应的值,不仅仅是字符串类型,可以是所有的数据类型:int、json、string、boolean等等,甚至于其值可以是一个嵌入的另一个文档。

对于文档中的键,有几点需要注意
(1)键不能含有”\0”(空字符)。因为这个字符在文档中表示键的结尾。
(2)”.”和”$”是保留字段,非常不建议使用,只有在特定的情况下才会使用,比如”.”字符,该字符在mongoDB中表示取其子字段,所以如果你在键中使用了该字段,取的就不是该字段了。比如{”data.page”:1},这时候我们如果取”data.page”的值,就不是”data.page”这个键了,而是”page”字段的值了。
(3)_开头的键也是保留的,不建议使用。
(4) 键区分大小写,”Foo”和”foo”是两个不同的键。
(5)一个文档中键不能重复。

在MongoDB的文档中,其数据是非常灵活的,两个完全不一样的文档,可以放在同一个集合中,这在关系型数据库中,是不能实现的,除非创建一个所有字段都包含的表。在MongoDB的文档中则不需要。这也是MongoDB的一个非常nice的地方。

集合(collection)

集合表示多个文档的集合,相当于关系型数据库的表(table),使用集合对象,可以对集合中的文档进行增删改查操作。

访问集合有两种方式:
(1)在mongoDB shell中直接使用db.collectionName,比如db.mycollection.find()实现查找mycollection集合中的所有文档。注:该方式只适用与shell中
(2) mycollection = db.getCollection("mycollection");mycollection.find()该方法可以在JavaScript文件和shell中使用

MongoDB提供了很多方法,用于对集合进行一系列的操作,大家可以点击上面的链接查看最新的方法。

数据库(Database)

该数据库与MonogDB数据库不是一个东西,MongoDB数据库表示的是MongoDB这个产品,以及它的用处。但是此处的数据库,是MongoDB里面的一个结构对象,我们可以参考MySql数据库的数据库。

MongoDB中的数据库,它可以让我们执行添加用户、访问集合等操作。

在MongoDB中创建一个数据库有两种方法:
(1)在MongoDB shell中使用use database命令,该命令是如果存在该数据库,MongoDB会将焦点切换到该数据库,如果该数据库不存咋,则会隐式的创建该数据库,并且将焦点切换到该数据库,然后我们可以操作该数据库中集合与数据等。当我们把焦点切换到该数据库时,我们就可以使用db关键字代表当前数据库,并且使用该关键字可以调用数据库的方法,比如:db.createUser(...).注:该方法只能在MongoDB shell中使用
(2)我们可以使用Connection对象的方法getDB()来创建一个Database对象,比如:con = new Mongo("localhost"); mdb = con.getDB("myDB"); mdb.getName();或者mdb = connect("localhost:27017/myDB"); mdb.getName()。该方法可以在shell中使用,也可以在JavaScript文件中使用。

想要了解更多的方法,可以点击上面的链接。

1. 管理数据库

显示数据库列表
想要显示当前系统中的数据库列表,我们可以使用show dbs命令

切换到其他数据库
在MongoDB中,我们操作某个数据库中的集合、文档、用户的时候,有一个前提,就是当前的db句柄,必须在要操作的数据所在的数据库上,也就是说当前数据库必须是操纵的数据所在的数据库,那么我们想要操作别的数据库的数据,就需要切换数据库句柄,我们可以使用db.getSiblingDB(database)方法和use database。查看当前数据库句柄,我们可以直接使用db命令。

创建数据库
上面说了,创建数据库我们可以使用use database命令,MongoDB支持隐式的创建数据库,当然我们也可以使用db.createCollection(database)方法创建数据库。

删除数据库
删除数据库,首先需要将db句柄切换到要删除的数据库中,然后调用db.dropDatabase()方法
注:删除数据库,并不会修改db句柄,所以大家在删除当前数据库时,下一步想要操作别的数据库,大家还需要切换下db句柄。

2.管理集合

创建集合
我们想要在某个数据库中创建一个集合,需要先将当前db句柄切换到那个数据库上,然后运行db.createCollection(name, options)方法创建集合,其详细的介绍可以查看官网说明

删除集合
要删除一个集合,我们可以使用db.collection.drop()方法,如果我们只是想清空当前集合中的数据,而不是删除当前集合,我们可以使用db.collection.remove()方法

3.示例数据集
接下来的学习中,我们会进行大量的实验操作,那么需要大量的数据进行支持,所以我将《MongoDB入门经典》中的实例数据集下载了下来,大家可以自行下载,然后运行到自己的MongoDB中。密码是hmhg。

大家下载下来之后,大家可以找到hour05/generate_words.js,这个文件,如图:
这里写图片描述
这个文件就是数据集的生成文件,我们只需要运行下这个文件就可以了。
或者自己建一个文件,然后将下面代码复制进去就可以了:

var vowelArr = "aeiou";
var consonantArr = "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";
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 (consonantArr.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.remove();
db.word_stats.ensureIndex({word: 1}, {unique: true});
db.word_stats.insert(wordObjArr);

接下来介绍,加载该文件的步骤:

1.首先我们先在一个合适的位置放这些文件,这个看个人喜好了。
2.启动MongDB
3.如果当前MongoDB开启了身份验证,修改上面的文件,倒数第四行db = connect("localhost/words")—-db = connect("localhost/words","yfl","yfl")(此处添加自己的数据库验证,如果words没有当前用户,我们首先需要在words创建该用户,并且该用户需要有读写权限)。另外倒数第三行db.word_stats.remove();如果你没有words数据库,或者有words数据库,但是没有word_stats集合 该句请删除。
4.然后执行下面命令mongo d:\MongoDB\js\hour05\generate_words.js,其中后面的路径,请替换成自己的文件路径。
执行完成之后可以查询到数据:
这里写图片描述这里写图片描述
做好准备我们就可以做一些练习了。

展开阅读全文

没有更多推荐了,返回首页