MongoDB入门—— 如何使用java语言查找某个文档中不同的字段值?
方法:
MongoDB中的集合查询(获取一组文档中某个字段的不同值列表)
运用方法:DBCollection对象方法中的 distinct() 语句:
语句结构:distinct(key,[query])
key字符串,指定获取哪个字段的不同值;query:包含标准查询选项的对象,指定了要从哪个文档中获取不同的字段值
举例说明:
如下是 inventory 集合的数据
{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
> db.inventory.distinct(“dept”) //获取dept字段的不重复值
结果:[“A”,”B”]
> db.inventory.distinct(“item.sku”) //获取item子字段sku的不重复值
结果:[“111”,”222”,”333”]
>db.inventory.distinct(“sizes”) //获取数组格式字段的不重复值
结果:[“M”,”S”,”L”]
>db.inventory.distinct(“item.sku”,{dept:”A”}) //满足dept为A数据的item字段的子字段的不重复值
结果:[“111”,”333”]
运行过程:
- 下载并安装JAVA MongoDB驱动程序并编辑环境变量
- 在MongoDB控制台导入需要的包
- 启动MongoDB服务器
- 重新打开一个cmd控制台 执行创建数据库脚本
cd 文件路径
mongo 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);
- words数据库创建成功
- 执行java文件(注意 这里需要导入AVA MongoDB驱动程序的jar包,且build path)
- 执行程序
附录:JAVA程序代码(eclipse下)
package mongodb; import java.util.List; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.MongoClient; public class javaFindDistinct { public static void main(String[] args) { try { MongoClient mongoClient = new MongoClient("localhost", 27017); //数据连接池 DB db = mongoClient.getDB("words"); DBCollection collection = db.getCollection("word_stats"); //获取集合 javaFindDistinct.sizesOfAllWords(collection); //找到并显示所有单词的各种长度 javaFindDistinct.sizesOfQWords(collection); //找出并显示以q打头的单词的各种长度 javaFindDistinct.firstLetterOfLongWords(collection); //找出并显示长度超过12的单词的各种长度 } catch (Exception e) { System.out.println(e); } } public static void sizesOfAllWords(DBCollection collection){ List<Double> results = collection.distinct("size"); //获取size字段的不同值 System.out.println("\nDistinct Sizes of words: "); System.out.println(results.toString()); } public static void sizesOfQWords(DBCollection collection){ BasicDBObject query = new BasicDBObject("first", "q"); List<Double> results = collection.distinct("size", query); //运用distinct对象,distinct(key,[query]) System.out.println("\nDistinct Sizes of words starting with Q: "); System.out.println(results.toString()); } public static void firstLetterOfLongWords(DBCollection collection){ BasicDBObject query = new BasicDBObject("size", new BasicDBObject("$gt", 12)); //利用 BasicDBObject进行拼接,拼接两个对象判断是否超过12,BasicDBObject(字段名,字段值) List<String> results = collection.distinct("first", query); System.out.println("\nDistinct first letters of words longer " + "than 12 characters: "); System.out.println(results.toString()); } }
如果您因为文章内容想联系我,请您发送相关内容至邮箱1634506078@qq.com,或者直接私信我的博客园账号。
谢谢。