Java Connection to MongoDB database

Source: Internet
Author: User
Tags mongoclient log4j

This period of time to try MongoDB, feel very easy to use, convenient, compared to relational database advantages are also very large, so try to use Java to connect MongoDB, and carried out

Basic additions and deletions to check the operation.

First, connect to the database in the console and view the database with several tables.

Now, to create a new MAVEN project, the dependencies in Pom.xml are as follows:

<!--WICKET DEPENDENCIES--><dependency><groupid>org.apache.wicket</groupid>< artifactid>wicket</artifactid><version>${wicket.version}</version></dependency>< !--OPTIONAL <dependency><groupId>org.apache.wicket</groupId><artifactId> Wicket-extensions</artifactid><version>${wicket.version}</version></dependency>--> <!--LOGGING dependencies-log4j--><dependency><groupid>org.slf4j</groupid><artifactid >slf4j-log4j12</artifactId><version>1.4.2</version></dependency><dependency> <groupid>log4j</groupid><artifactid>log4j</artifactid><version>1.2.14</ version></dependency><!--JUNIT dependency for testing--><dependency><groupid>junit< /groupid><artifactid>junit</artifactid><version>4.12</version></dependency> <!--MongoDB for TEST--&Gt;<dependency><groupid>org.mongodb</groupid><artifactid>mongo-java-driver</ artifactid><version>3.0.2</version></dependency><!--JETTY DEPENDENCIES for testing <dependency><groupId>org.mortbay.jetty</groupId><artifactId>jetty</artifactId> <version>${jetty.version}</version><scope>provided</scope></dependency>< Dependency><groupid>org.mortbay.jetty</groupid><artifactid>jetty-util</artifactid> <version>${jetty.version}</version><scope>provided</scope></dependency>< dependency><groupid>org.mortbay.jetty</groupid><artifactid>jetty-management</ artifactid><version>${jetty.version}</version><scope>provided</scope></ Dependency></dependencies>

Now, in the source folder, create a newMongoDB class

   Write the following nine methods, the following methods are the main connection, adding and removing changes to check the operation:
   
Package Com.haizhi.mongodb.connect;import Com.mongodb.*;import Java.util.list;import java.util.map;import java.util.set;/** * Created by Xiaxuan on 15/7/17. */public class MongoDB {//1, connect to database public mongoclient Getmongo () {//1, connect to MongoDb database mongoclient MONGO        =new mongoclient ("127.0.0.1", 27017);    return MONGO;        }//2, gets the specified database public db getdb (String DbName) {mongoclient Mongo=getmongo ();    Return Mongo.getdb (DbName);        }//3, display all databases in database public void showdb () {mongoclient Mongo=getmongo ();        Show all Databases list<string> dbs=mongo.getdatabasenames ();        for (String Database:dbs) {System.out.println (database); }}//4, get a table public dbcollection getTable (DB db,string tableName) {//If the table does not exist, MongoDB will create a Dbcollec        tion table=db.getcollection ("users");    return table; }//5, display all tables in the database public void Showtables (DB db) {//Displays all tables in the selected database Set<string> tables=db.geTcollectionnames ();        for (String coll:tables) {System.out.println (coll); }}//6, add a record public void insert (map<string,object> map,dbcollection table) {Basicdbobject document        =new Basicdbobject ();        For (Object Key:map.keySet ()) {document.put (String) key, Map.get (key));    } table.insert (document); }//7, finds and displays a record public void search (basicdbobject basicdbobject,dbcollection table) {dbcursor dbcursor=table.f        IND (Basicdbobject);        while (Dbcursor.hasnext ()) {System.out.println (Dbcursor.next ());    } System.out.println ("End"); }//8, update a record public void update (Basicdbobject query,basicdbobject newdocument,dbcollection table) {Basicdbobj        ECT updateobj=new basicdbobject ();        Updateobj.put ("$set", newdocument);    Table.update (query, updateobj); }//9, delete a record public void delete (Basicdbobject basicdbobject,dbcollection table) {Table.remove (basicdbobject); }}

   Now, in the test folder, create a new testing class:
   
  Testinsert:
  
Package Com.haizhi.testmongodb;import Com.haizhi.mongodb.connect.mongodb;import Com.mongodb.dbcollection;import Com.mongodb.db;import com.mongodb.mongoclient;import org.junit.test;import Java.util.hashmap;import java.util.Map ;/** * Created by Xiaxuan on 15/7/17. */public class Testinsert {    @Test public    void Insert () {        MongoDB mongodb=new MongoDB ();        Mongoclient Mongo=mongodb.getmongo ();        DB db=mongodb.getdb ("Mongotest");        Dbcollection table=mongodb.gettable (DB, "users");        Map<string,object> map=new hashmap<string, object> ();        Map.put ("id", 3);        Map.put ("name", "Xiaxuan");        Map.put ("Age", a);        Map.put ("Sex", true);        Map.put ("nickname", "Bingwen");        Mongodb.insert (map,table);    }}

After executing the program, search in the database:

This record is inserted successfully in the database.

Now test the query:

Testsearch:

Package Com.haizhi.testmongodb;import Com.haizhi.mongodb.connect.mongodb;import Com.mongodb.basicdbobject;import Com.mongodb.dbcollection;import com.mongodb.mongoclient;import com.mongodb.db;import org.junit.Test;/** * Created by Xiaxuan on 15/7/17. */public class Testsearch {    @Test public    void Testsearch () {        MongoDB mongodb=new MongoDB ();        Mongoclient Mongo=mongodb.getmongo ();        DB db=mongodb.getdb ("Mongotest");        Dbcollection talbe=mongodb.gettable (DB, "users");        Basicdbobject basicdbobject=new basicdbobject ();        Basicdbobject.append ("name", "Xiaxuan");        Mongodb.search (Basicdbobject,talbe);    }}

Successfully queried to two data.

Modify the test source program and delete the same basically, here just paste out the source code, no longer demonstrate the specific effect.

Testupdate:

Package Com.haizhi.testmongodb;import Com.haizhi.mongodb.connect.mongodb;import Com.mongodb.basicdbobject;import Com.mongodb.db;import Com.mongodb.dbcollection;import Com.sun.xml.internal.rngom.parse.host.base;import org.junit.test;/** * Created by Xiaxuan on 15/7/17. */public class Testupdate {    @Test public    Void Update () {        MongoDB mongodb=new MongoDB ();        DB db=mongodb.getdb ("Mongotest");        Dbcollection table=mongodb.gettable (DB, "users");        Basicdbobject query=new basicdbobject ();        Query.put ("name", "Xiaxuan");        Basicdbobject newdocument=new basicdbobject ();        Newdocument.put ("name", "Bingwen");        Mongodb.update (query,newdocument,table);    }}

testdelete:

Package Com.haizhi.testmongodb;import Com.haizhi.mongodb.connect.mongodb;import Com.mongodb.basicdbobject;import Com.mongodb.db;import com.mongodb.dbcollection;import org.junit.test;/** * Created by Xiaxuan on 15/7/17. */public class Testdelete {    @Test public    void Delete () {        MongoDB mongodb=new MongoDB ();        DB db=mongodb.getdb ("Mongotest");        Dbcollection table=mongodb.gettable (DB, "users");        Basicdbobject basicdbobject=new basicdbobject ();        Basicdbobject.put ("name", "Xiaxuan");        Mongodb.delete (basicdbobject,table);    }}
The connection MongoDB, as well as the basic addition and deletion to change the operation, is these, the connection MongoDB, the operation, the basic operation is still relatively simple.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Connection to MongoDB database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.