[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 www.

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.

Speaking of Java database operations, 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 it.


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. except exception; public class foreign factory {private static foreign factory; private foreign factory () {} public static foreign factory getInstance () {if (foreign factory = null) {foreign factory = new foreign factory ();} return mongoFactory;} public Mongo getMongo () {Mongo mongo = null; try {mongo = new Mongo (SystemConstant. configure. HOST, SystemConstant. configure. PORT);} catch (UnknownHostException e) {e. printStackTrace ();} catch (except exception 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; @ BeforeClasspublic 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.


  • 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.

    Basic query (primary key query, query set, and conditional query)

    // Query the public void test3 () {BasicDBObject query = new BasicDBObject (); query. put ("_ id", "00001"); List 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 [] {"Discovery Ming", "Taiji"}); List 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.

    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 );}

    Delete operation

    // Delete the public void test7 () {BasicDBObject query = new BasicDBObject (); query. put ("_ id", "000010"); dao. delete (query); List 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 records (document objects ).

    Multi-condition Query

    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.