crud mongodb

Upload: leonardo-villegas-farfan

Post on 20-Feb-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/24/2019 Crud Mongodb

    1/13

    MongoDB Java CRUD Example TutorialPankajAugust 9, 2014MongoDB

    Earlier we looked how to install MongoDB in Unix a!hinesand exe!uted soe !oands "ro terinal# $oda%

    we will look into the MongoDB Java Driver"eatures and how to &er"or !oon o&erations with exa&les o"

    '(UD )'reate, (ead, U&date, Delete* o&erations#1# MongoDB +aa Drier Download

    2# 'reating MongoDB 'onne!tion

    -# 'onne!tion to MongoDB Data.ase

    4# MongoDB and 'olle!tions

    /# MongoDB +aa '(UD Exa&le

    1. MongoDB Java Driver Download

    " %ou hae aen &roje!t, just add .elow de&enden!% to in!lude MongoDB jaa drier into %our a&&li!ation#

    1

    234

    5

    org.mongodb mongo-java-driver 2.12.3

    " %ou hae a standalone &roje!t, %ou !an download MongoDB +aa Drier "ro this linkand in!lude it in

    %our &roje!t .uild &ath#

    ow lets go through soe .asi! usage o" MongoDB jaa drier and then we will look into MongoDB Java

    Example&rogra "or '(UD o&erations#

    http://www.journaldev.com/author/pankajhttp://www.journaldev.com/dev/database/mongodbhttp://www.journaldev.com/dev/database/mongodbhttp://www.journaldev.com/3849/how-to-install-mongodb-on-unix-linux-systemshttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongodb-java-driver-downloadhttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongoclient-connectionhttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongoclient-databasehttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongodb-collectionshttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongodb-java-examplehttp://search.maven.org/remotecontent?filepath=org/mongodb/mongo-java-driver/2.12.3/mongo-java-driver-2.12.3.jarhttp://www.journaldev.com/dev/database/mongodbhttp://www.journaldev.com/3849/how-to-install-mongodb-on-unix-linux-systemshttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongodb-java-driver-downloadhttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongoclient-connectionhttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongoclient-databasehttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongodb-collectionshttp://www.journaldev.com/3963/mongodb-java-crud-example-tutorial#mongodb-java-examplehttp://search.maven.org/remotecontent?filepath=org/mongodb/mongo-java-driver/2.12.3/mongo-java-driver-2.12.3.jarhttp://www.journaldev.com/author/pankaj
  • 7/24/2019 Crud Mongodb

    2/13

    2. Creating MongoDB Connection

    MongoClientis the inter"a!e .etween our jaa &rogra and MongoDB serer, its used to !reate

    !onne!tion, !onne!t to data.ase, retriee !olle!tion naes and !reate3read3u&date3delete data.ase,

    !olle!tions, do!uent et!#

    ne o" the MongoDB jaa drier "eature like ost is that its thread sa"e, so we !an !reate an instan!e

    o" Mongo'lienton!e and reuse it# Een i" ulti&le thread a!!esses it siultaneousl%, a !onne!tion is returned

    "ro the internal !onne!tion &ool aintained .% it# 5or eer% re6uest to the DB )7nd, insert et!* the +aa

    thread will o.tain a !onne!tion "ro the &ool, exe!ute the o&eration, and release the !onne!tion# $his

    eans the !onne!tion )so!ket* used a% .e di8erent ea!h tie#

    Below are soe o" the !oon ethods to !onne!t to a MongoDB serer#

    1

    23

    4

    5

    678

    910

    MongoCient mongoCient ! ne"MongoCient#$% //connects to defaut &ost and port i.e 12'.(.(.1)2'(1'// orMongoCient mongoCient ! ne"MongoCient# *oca&ost*$% //connects to defaut port i.e 2'(1'// orMongoCient mongoCient ! ne"MongoCient# *oca&ost*+ 2'(1'$% // s&oud use t&is a"ays

    // or+ to connect to a repica set+ "it& auto-discovery of t&e primaryMongoCient mongoCient ! ne"MongoCient#,rrays.asist#ne"erver,ddress#*oca&ost*+ 2'(1'$+ ne"erver,ddress#*oca&ost*+ 2'(1$+ ne"erver,ddress#*oca&ost*+ 2'(10$$$%

    3. Connection to MongoDB Dataa!e

    n!e we get the !onne!tion to MongoDB serer, next ste& is to !reate the !onne!tion to the data.ase, as

    shown .elow# ote that i" data.ase is not &resent, MongoDB will !reate it "or %ou#

  • 7/24/2019 Crud Mongodb

    3/13

    1

    2

    MongoCient mongo ! ne"MongoCient#*oca&ost*+ 2'(1'$% db ! mongo.get#*journadev*$%

    Mongo'lient &roide a use"ul ethod to get all the data.ase naes, as shown .elow#

    12

    3

    MongoCient mongo ! ne"MongoCient#*oca&ost*+ 2'(1'$%ist dbs ! mongo.getatabaseames#$%ystem.out.printn#dbs$% // 4journadev+ oca+ admin5

    e !an hae user:&assword .ased authenti!ation "or data.ases, in that !ase we need to &roide

    authori;ation !redentials like .elow#

    1

    23

    4

    56

    78

    MongoCredentia journadev,ut& ! MongoCredentia.create6ainCredentia#*pan7aj*+ *journadev*+ *pan7aj12MongoCredentia test,ut& ! MongoCredentia.create6ainCredentia#*pan7aj*+ *test*+ *pan7aj123*.toC&ar,rrist aut&s ! ne",rrayist#$%aut&s.add#journadev,ut&$%aut&s.add#test,ut&$%

    erver,ddress server,ddress ! ne"erver,ddress#*oca&ost*+ 2'(1'$%MongoCient mongo ! ne"MongoCient#server,ddress+ aut&s$%

    " %ou are using older ersions, %ou need to &roide authenti!ation details a"ter getting the DB o.je!t like

    .elow#

    1

    23

    MongoCient mongo ! ne"MongoCient#*oca&ost*+ 2'(1'$% db ! mongo.get#*journadev*$%booeanaut& ! db.aut&enticate#*pan7aj*+ *pan7aj123*.toC&ar,rray#$$%

  • 7/24/2019 Crud Mongodb

    4/13

    e !an dro& a data.ase either .% using Mongo'lientdro&Data.ase)>tring d.*ethod or .% DBdro&Data.ase)*ethod#

    >in!e we are dro&&ing the data.ase, i &re"er to use Mongo'lient ethod#

    ". MongoDB and Collection!

    Eer% data.ase !an hae ;ero or ulti&le !olle!tions, the% are like ta.les in relational data.ase serers

    ex!e&t that %ou dont hae s&e!i7! "orat o" data# $hink o" it like a generi! list s list o" >trings in ters o"

    jaa &rograing language#

    e !an get all the !olle!tions naes using .elow !ode#

    12

    34

    5

    MongoCient mongo ! ne"MongoCient#*oca&ost*+ 2'(1'$% db ! mongo.get#*journadev*$%

    et coections ! db.getCoectionames#$%ystem.out.printn#coections$% // 4datas+ names+ system.inde8es+ users5

    e !an get a s&e!i7! !olle!tion .% &roiding its nae, as shown .elow#

    12

    db ! mongo.get#*journadev*$%Coection co ! db.getCoection#*users*$%

    Again i" the !olle!tion doesnt exist, MongoDB will !reate it "or %ou# All the data in MongoDB goes into soe

    !olle!tion, so at this &oint we are read% to &er"or insert3u&date3delete o&erations#

    e !an use DB'olle!tiondro&)*ethod to dro& a !olle!tion "ro the data.ase#

    #. MongoDB Java Example

  • 7/24/2019 Crud Mongodb

    5/13

    Een though we !an work on an% alid +> do!uent in MongoDB !olle!tion, in real li"e we hae P+

    !lasses that are a&&ed with these data# >o will !reate a jaa .ean and use it "or % exa&les#

    User.java

    1

    2

    345

    67

    8

    910

    1112

    13

    1415

    1617

    1819

    20

    2122

    2324

    25

    26

    pac7agecom.journadev.mongodb.mode%

    pubiccass9ser :

    privateintid%

    privatetring name% privatetring roe% privatebooeanis;mpoyee%

    pubicintgetId#$ :

    returnid% pubicvoidsetId#intid$ : t&is.id ! id% pubictring getame#$ : returnname% pubicvoidsetame#tring name$ : t&is.name ! name%

    pubictring get=oe#$ : returnroe% pubicvoidset=oe#tring roe$ : t&is.roe ! roe% pubicbooeanis;mpoyee#$ : returnis;mpoyee% pubicvoidset;mpoyee#booeanis;mpoyee$ : t&is.is;mpoyee ! is;mpoyee%

  • 7/24/2019 Crud Mongodb

    6/13

    27

    28

    2930

    3132

    3334

    ?ere is the !o&lete exa&le !lass showing all the '(UD o&erations one .% one#

    MongoDBExample.java

    12

    34

    5

    67

    89

    10

    1112

    1314

    1516

    17

    1819

    20

    pac7agecom.journadev.mongodb.main%

    importjava.net.9n7no"nost;8ception%

    importcom.journadev.mongodb.mode.9ser%importcom.mongodb.asic?bjectuider%importcom.mongodb.%importcom.mongodb.Coection%importcom.mongodb.Cursor%importcom.mongodb.?bject%importcom.mongodb.MongoCient%importcom.mongodb.@rite=esut%

    pubiccassMongo;8ampe :

    pubicstaticvoidmain#tring45 args$ t&ro"s9n7no"nost;8ception :

    9ser user ! create9ser#$%

    ?bject doc ! create?bject#user$%

    MongoCient mongo ! ne"MongoCient#*oca&ost*+ 2'(1'$%

    db ! mongo.get#*journadev*$%

  • 7/24/2019 Crud Mongodb

    7/13

    21

    22

    2324

    2526

    2728

    29

    3031

    3233

    34

    3536

    3738

    3940

    41

    42

    434445

    46

    4748

    4950

    5152

    Coection co ! db.getCoection#*users*$%

    //create user

    @rite=esut resut ! co.insert#doc$% ystem.out.printn#resut.get9psertedId#$$% ystem.out.printn#resut.get#$$% ystem.out.printn#resut.is9pdate?f;8isting#$$% ystem.out.printn#resut.getastConcern#$$%

    //read e8ampe ?bject Auery ! asic?bjectuider.start#$.add#*Bid*+ user.getId#$$.get#$% Cursor cursor ! co.find#Auery$% "&ie#cursor.&ase8t#$$: ystem.out.printn#cursor.ne8t#$$%

    //update e8ampe

    user.setame#*6an7aj umar*$% doc ! create?bject#user$% resut ! co.update#Auery+ doc$% ystem.out.printn#resut.get9psertedId#$$% ystem.out.printn#resut.get#$$% ystem.out.printn#resut.is9pdate?f;8isting#$$% ystem.out.printn#resut.getastConcern#$$%

    //deete e8ampe

    resut ! co.remove#Auery$% ystem.out.printn#resut.get9psertedId#$$% ystem.out.printn#resut.get#$$% ystem.out.printn#resut.is9pdate?f;8isting#$$% ystem.out.printn#resut.getastConcern#$$%

    //cose resources

    mongo.cose#$%

    privatestatic?bject create?bject#9ser user$ :

  • 7/24/2019 Crud Mongodb

    8/13

    53

    54

    5556

    5758

    5960

    61

    6263

    6465

    66

    6768

    6970

    7172

    73

    74

    757677

    78

    7980

    81

    asic?bjectuider docuider ! asic?bjectuider.start#$%

    docuider.append#*Bid*+ user.getId#$$%

    docuider.append#*name*+ user.getame#$$% docuider.append#*roe*+ user.get=oe#$$% docuider.append#*is;mpoyee*+ user.is;mpoyee#$$% returndocuider.get#$%

    privatestatic9ser create9ser#$ :

    9ser u ! ne"9ser#$% u.setId#2$% u.setame#*6an7aj*$% u.set;mpoyee#true$% u.set=oe#*C;?*$% returnu%

    A sa&le exe!ution results in "ollowing out&ut#

  • 7/24/2019 Crud Mongodb

    9/13

    1

    2

    34

    56

    78

    9

    1011

    1213

    nu(fase@riteConcern : *getasterror*) 1 / #Continue on errorD fase$: *Bid*) 2 + *name*) *6an7aj*+ *roe*) *C;?*+ *is;mpoyee*) truenu1true

    @riteConcern : *getasterror*) 1 / #Continue on errorD fase$nu1fase@riteConcern : *getasterror*) 1 / #Continue on errorD fase$

    oti!e that a saing User id with _idnae, this is a resered ke% "or the &riar% ke% o" an% re!ord in the

    !olle!tion# " we dont &roide one, MongoDB will !reate one "or us# ts like se6uen!er or auto in!reent

    !olun in relational data.ase ta.les#

    >in!e a deleting the !reated re!ord, "urther exe!ution wont !ause an% issues# But i" there are du&li!ate

    re!ord, then we will get .elow errors#

    1

    23

    45

    67

    8

    910

    ;8ception in t&read *main*com.mongodb.Mongo;8ceptionEupicateey) : *server9sed*) *oca&ost)2'(1'*+ *err*) *insertocument )) caused by )) 11((( ;11((( dupicate 7ey error inde8) journadev.users.EBidB *code*) 11((( at com.mongodb.Command=esut.get@rite;8ception#Command=esut.java)$ at com.mongodb.Command=esut.get;8ception#Command=esut.java)'0$ at com.mongodb.CoectionImp.transateu7@rite;8ception#CoectionImp.java)31F$ at com.mongodb.CoectionImp.insert#CoectionImp.java)10$ at com.mongodb.CoectionImp.insert#CoectionImp.java)1GH$ at com.mongodb.Coection.insert#Coection.java)03$ at com.mongodb.Coection.insert#Coection.java)'$ at com.mongodb.Coection.insert#Coection.java)12($ at com.journadev.mongodb.main.Mongo;8ampe.main#Mongo;8ampe.java)2'$

  • 7/24/2019 Crud Mongodb

    10/13

    11

    12

    $hats all "or getting %our started with MongoDB +aa Drier, we will look into ore "eatures in next &osts

  • 7/24/2019 Crud Mongodb

    11/13

    pac7agecom.devjavasource.mongodb.eo@ord;8ampe%

    importjava.uti.ate%

    importorg.bson.ocument%

    importcom.mongodb.asic?bject%importcom.mongodb.MongoCient%importcom.mongodb.cient.indIterabe%importcom.mongodb.cient.MongoCoection%importcom.mongodb.cient.MongoCursor%importcom.mongodb.cient.Mongoatabase%

    pubiccass,pp : pubicstaticvoidmain#tring45 args$ :

    MongoCient mongoCient ! nu%

    try:

    // Jet MongoCient Connect to Mongo mongoCient ! ne"MongoCient#*oca&ost*+ 2'(1'$%

    // Jet database

    // If database doesnKt e8ists+ Mongo "i create it for you Mongoatabase db ! mongoCient.getatabase#*devjavasource*$%

    // Jet coection / tabe from KdevjavasourceK

    // If coection doesnKt e8ists+ Mongo "i create it foryou MongoCoection coection !db.getCoection#*orders*$%

    // =etrieve a t&e documents of a specified coection

    retrieve#coection$%

    // Insert a ne" document into Mongo

    ystem.out.printn#*LnMondo - Insert operationLn*$% insert#coection$% retrieve#coection$%

    // 9pdate a document

    ystem.out.printn#*LnMondo - 9pdate operationLn*$% update#coection$%

    retrieve#coection$%

    ystem.out.printn#*LnMondo - eete operation

    Ln*$% coection.deete?ne#ne"ocument#*orderBid*+ *F1'(FG21*$$% retrieve#coection$%

    catc8ception e$ :

    e.printtac7Nrace#$%

  • 7/24/2019 Crud Mongodb

    12/13

    finay: mongoCient.cose#$%

    privatestaticvoidupdate#finaMongoCoection

    inCoection$ : inCoection.update?ne#ne"ocument#*orderBid*+ *F1'(FG21*$+ ne"ocument#*Eset*+ ne"ocument#*status*+ *;8ecuted*$$ .append#*Ecurrentate*+ ne"ocument#*astModified*+ true$$$%

    privatestaticvoidinsert#finaMongoCoection

    inCoection$ : finaocument document ! ne"ocument#$% document.put#*orderBid*+ *F1'(FG21*$% document.put#*customerBname*+ *tuart ,damson*$% document.put#*status*+ *?rdered*$%

    finaasic?bject addressocument ! ne"asic?bject#$%

    addressocument.put#*street*+ *13t& treet+ 2 ane*$% addressocument.put#*Oipcode*+ *3((1F*$% addressocument.put#*buiding*+ *,venue 6ar7*$% document.put#*address*+ addressocument$%

    finaasic?bject itemsocument ! ne"asic?bject#$%

    itemsocument.put#*itemBid*+ *Item1(1*$% itemsocument.put#*count*+ 21$% itemsocument.put#*date*+ ne"ate#$$% document.put#*Items*+ itemsocument$%

    inCoection.insert?ne#document$%

    privatestaticvoidretrieve#finaMongoCoection

    inCoection$ : finaindIterabe itr ! inCoection.find#$% finaMongoCursor mongoItr ! itr.iterator#$% "&ie#mongoItr.&ase8t#$$ : finaocument doc ! mongoItr.ne8t#$% printit#doc$%

    privatestaticvoidprintit#finaocument inoc$ :

    ystem.out.printn#*?rder etais are)*$% ystem.out.printn#*!!!!!!!!!!!!!!!!!!!!*$% inoc.entryet#$.stream#$.for;aceac& -> : ystem.out.printn#*ey ) *P eac&.getey#$$% ystem.out.printn#*Qaue ) *P eac&.getQaue#$$%

    $%

  • 7/24/2019 Crud Mongodb

    13/13