[MongoDB learning logs] Java CRUD operations on MongoDB

Source: Internet
Author: User

Speaking of Java operations on databases, we will naturally think of Sun's well-known brand JDBC. For NoSQL databases such as MongoDB, there are currently no standards such as JDBC.

This article analyzes the current situation and looks forward to http://www.csdn.net/article/2012-06-21/2806842


Back to the topic record familiar with MongoDB for Java language operation interface mongo-java-driver.jar


1. The basic foundation remains unchanged. Connect to the database

2. Basic database operations remain unchanged, CRUD

3. The provided interfaces and implementation class names are changed. The operation objects are very different.

4. The change is that there is no standard Java standard API for operating MongoDB.


The Java operation API provided by MongoDB is a Java translation of Mongo database commands, familiar with Mongo commands, and familiar with the basic idea of Java database operations. It is easy to master basic operations.


  • Database Connection

    package com.im;public final class SystemConstant {    public static final class Configure {        public static final String HOST = "127.0.0.1";                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          public static final int PORT = 27017;        public static final String USERNAME = "";        public static final String PASSWORD = "";        public static final String DATABASE = "im";    }}
    package com.im;import java.net.UnknownHostException;import com.mongodb.Mongo;import com.mongodb.MongoException;public class MongoFactory {    private static MongoFactory mongoFactory;    private MongoFactory() {    }    public static MongoFactory getInstance() {        if (mongoFactory == null) {            mongoFactory = new MongoFactory();        }        return mongoFactory;    }    public Mongo getMongo() {        Mongo mongo = null;        try {            mongo = new Mongo(SystemConstant.Configure.HOST,                    SystemConstant.Configure.PORT);        } catch (UnknownHostException e) {            e.printStackTrace();        } catch (MongoException e) {            e.printStackTrace();        }        return mongo;    }}


Host Name, port number, and database name. The Mongo object in the above Code is equivalent to the Connection object.


  • Database Operations

    Each of the following methods represents a test

    Test class initialization method:

    private static BaseDao dao;    @BeforeClass    public static void start() {        dao = new BaseDao("users","uf");    }

    BaseDao is a DAO object encapsulated by common Mongo methods for database operations. The Code will be included at the end of this article.


650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/2215252E5-0.gif "alt =" j_0001.gif "/> insert:


// Add a record public void test1 () {BasicDBObject jo = new BasicDBObject (); jo. put ("_ id", "00001"); jo. put ("name", "Tomcat"); jo. put ("age", 22); jo. put ("interest", new String [] {"Ming", "Taiji", "football"}); int actual = dao. insert (jo); System. out. println (actual); Assert. assertEquals (1, actual );}


// Add multiple Records public void test2 () {int actual = 0; int size = 0; for (int I = 2; I <11; I ++) {BasicDBObject jo = new BasicDBObject (); jo. put ("_ id", "0000" + I); jo. put ("name", "Tomcat _" + I); jo. put ("age", I * 2); jo. put ("interest", new String [] {"Ming", "Taiji"}); actual + = dao. insert (jo); size ++;} Assert. assertEquals (size, actual );}



The BasicDBObject object is the basic implementation class of Mongo BSONObject, And the BSONObject object is saved to the database in the form of a Map in the Key-Value format.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/2215252E5-0.gif "alt =" j_0001.gif "/> basic query primary key query, query set, condition query)

// Query the public void test3 () {BasicDBObject query = new BasicDBObject (); query. put ("_id", "00001"); List <DBObject> dboList = dao. query (query); System. out. println (dboList. get (0 ). toString (); Assert. assertEquals (1, dboList. size ();} // fuzzy query, counting the number of record results public void test4 () {BasicDBObject query = new BasicDBObject (); query. put ("interest", new String [] {"Ming", "Taiji"}); long count = dao. getCount (query); Assert. assertEquals (9, count);} // module query. The query result set is public void test5 () {BasicDBObject query = new BasicDBObject (); query. put ("interest", new String [] {"Ming", "Taiji"}); List <DBObject> dboList = dao. query (query); for (DBObject jo: dboList) {System. out. println (jo. toString ();} Assert. assertEquals (9, dboList. size ());}

The following figure shows the data of the database after the data is inserted. The data in the figure is the data of various tests, not the database after the operation of each method.

650) this. width = 650; "src =" http://img1.51cto.com/attachment/201312/213445907.png "title =" mongo-test-data.png "alt =" 415445907.png"/>


650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/2215252E5-0.gif "alt =" j_0001.gif "/> Update operation

The Mongo update operation requires two BasicDBObject objects, one being the object to be updated and the other being the updated object.

// Update the public void test6 () {BasicDBObject query = new BasicDBObject (); query. put ("_ id", "00001"); BasicDBObject jo = new BasicDBObject (); jo. put ("_ id", "00001"); jo. put ("name", "Jackson"); jo. put ("interest", new String [] {"Song", "Taiji", "Running"}); jo. put ("firends", new BasicDBObject [] {(BasicDBObject) dao. query (new BasicDBObject ("_ id", "00002 ")). get (0), (BasicDBObject) dao. query (new BasicDBObject ("_ id", "00002 ")). get (0)}); int actual = dao. update (query, jo); Assert. assertEquals (1, actual );}

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/2215252E5-0.gif "alt =" j_0001.gif "/> delete operation

// Delete the public void test7 () {BasicDBObject query = new BasicDBObject (); query. put ("_ id", "000010"); dao. delete (query); List <DBObject> dboList = dao. query (query); Assert. assertEquals (0, dboList. size ());}


Mongo is easier to delete. specifying a BasicDBObject as a matching condition will delete all matching document objects ).

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/2215252E5-0.gif "alt =" j_0001.gif "/> multi-condition Query

Query operations are more diverse and frequent in database CRUD operations. The Mongo Java driver encapsulates various condition queries of Mongo data and provides a QueryBuilder class, visualize the query operations in Mongo, use this class to create the conditions to be queried, and then perform basic queries.


// Query public void test8 () {BasicDBObject query = new BasicDBObject (); BasicDBObject condition = new BasicDBObject (); condition. put (QueryOperators. GTE, 10); query. put ("age", condition); List <DBObject> dboList = dao. query (query); for (DBObject jo: dboList) {System. out. println (jo. toString ();} Assert. assertEquals (5, dboList. size ();} public void test9 () {BasicDBObject query = new BasicDBObject (); BasicDBObject condition = new BasicDBObject (); condition. put (QueryOperators. GTE, 10); condition. put (QueryOperators. LTE, 16); query. put ("age", condition); List <DBObject> dboList = dao. query (query); for (DBObject jo: dboList) {System. out. println (jo. toString ();} Assert. assertEquals (4, dboList. size ();} public void test10 () {QueryBuilder qb = new QueryBuilder (); BasicDBObject query = (BasicDBObject) qb. and ("age "). greaterThanEquals (10 ). lessThanEquals (14 ). and ("interest "). in (new String [] {"Ming", "Taiji", "football "}). get (); List <DBObject> dboList = dao. query (query); for (DBObject jo: dboList) {System. out. println (jo. toString ());}}

The query condition in the test8 method is implemented by creating BasicDBObject. If there are more conditions, this operation will write a lot of code and it is not easy to associate each condition, the following test9 and test10 methods are implemented using QueryBuilder.




The above operations on Mongo data focus on preparing query conditions, inserting objects, deleting conditions, and updating conditions. The main reason is that Mongo database operations are not highly standardized as we used SQL statements, on the contrary, more attention is paid to how to translate Mongo command operations in programming languages, for the simple reason that there is no unified standard implementation.


As for the basic operations of the database, the Java driver of Mongo must naturally provide the most basic operation functions.


Attach the BaseDao code:


Package com. im. dao; import java. io. file; import java. io. IOException; import java. io. inputStream; import java. util. arrayList; import java. util. list; import com. im. export factory; import com. im. systemConstant; import com. mongodb. basicDBObject; import com. mongodb. DB; import com. mongodb. DBCollection; import com. mongodb. DBCursor; import com. mongodb. DBObject; import com. mongodb. writeResult; import com. mongodb. gridfs. gridFS; import com. mongodb. gridfs. gridFSDBFile; import com. mongodb. gridfs. gridFSInputFile; public class BaseDao {/*** database object */private DB db;/*** database document object is equivalent to a table in RDBMS) */private DBCollection dbCollection; /*** a collection of database files */private GridFS fs; public BaseDao (String docBucket, String fileBucket) {db = MongoFactory. getInstance (). getMongo (). getDB (SystemConstant. configure. DATABASE); this. dbCollection = db. getCollection (docBucket); if (fileBucket. endsWith ("") | fileBucket = null) {fileBucket = "fs";} this. setFs (new GridFS (db, fileBucket);}/*** insert document ** @ param jo * @ return */public int insert (DBObject jo) {WriteResult wr = dbCollection. save (jo); return wr. getN ();}/*** delete the matched document ** @ param jo */public void delete (DBObject jo) {dbCollection. remove (jo );} /***** update document ** @ param query * specifies the updated document * @ param jo * @ return */public int update (DBObject query, DBObject jo) {WriteResult wr = dbCollection. update (query, jo); return wr. getN ();}/*** query document ** @ param query * matched document * @ return */public List <DBObject> query (DBObject query) {DBCursor dbc = dbCollection. find (query); List <DBObject> joList = new ArrayList <DBObject> (); while (dbc. hasNext () {DBObject jo = dbc. next (); joList. add (jo);} return joList;}/*** storage file ** @ param File */public void saveFile (file File) {try {GridFSInputFile gif = fs. createFile (file); gif. save ();} catch (IOException e) {e. printStackTrace () ;}/ *** stores the input stream, and some specified description information ** @ param in * @ param id * @ param filename * file name * @ param contentType * file content type */public void saveFile (InputStream in, object id, String filename, Object contentType) {DBObject query = (DBObject) new BasicDBObject ("_ id", id); GridFSDBFile gff = fs. findOne (query); if (gff = null) {GridFSInputFile gif = fs. createFile (in); gif. setFilename (filename); gif. put ("_ id", id); gif. put ("contentType", contentType); gif. save () ;}}/*** query the file with the specified ID ** @ param id * @ return */public GridFSDBFile queryFile (Object id) {DBObject query = (DBObject) new BasicDBObject ("_ id", id); return fs. findOne (query);}/*** query the file with the specified file name ** @ param filename * @ return */public GridFSDBFile queryFile (String filename) {DBObject query = (DBObject) new BasicDBObject ("filename", filename); return fs. findOne (query);}/** query file ** @ param query * matched file * @ return */public List <GridFSDBFile> queryFile (DBObject query) {return fs. find (query);}/*** count the number of query results ** @ param query * query matched documents * @ return */public long getCount (DBObject query) {return dbCollection. getCount (query);} public GridFS getFs () {return fs;} public void setFs (GridFS fs) {this. fs = fs;} public DBCollection getDbCollection () {return dbCollection;} public void setDbCollection (DBCollection dbCollection) {this. dbCollection = dbCollection ;}}


This article is from the "wild horse red dust" blog and will not be reposted!

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.