Java Operation MongoDB Implementation curd

Source: Internet
Author: User
Tags bulk insert

Java Operation MongoDB
MongoDB, as a bullish, NoSQL memory database, does have a lot of advantages, and MongoDB can handle Internet applications with large data volumes, high concurrency, and weak transactions. Access to MongoDB reference to the next API to achieve the implementation of additions and deletions, MongoDB is object-oriented design, do not write SQL statements directly manipulate the API method can be implemented, the database statement is not good to write the dolls are blessed. Direct code:

Datatest.java

Package Com.zk.db;import Java.net.unknownhostexception;import Java.util.arraylist;import java.util.List;import Org.bson.types.objectid;import Org.junit.test;import Com.mongodb.basicdbobject;import Com.mongodb.DB;import Com.mongodb.dbcollection;import Com.mongodb.dbcursor;import Com.mongodb.dbobject;import Com.mongodb.Mongo;import com.mongodb.mongoexception;/** * Test MongoDB curd * @author ZK * @time April 24, 2015 23:19:15 */public class Datatest {//    1. Establish a Mongo database connection object static Mongo connection = NULL;    2. Create a connection to the related database static DB db = null;            Static {try {connection = new Mongo ("127.0.0.1:27017");//default link address} catch (Exception e) {        E.printstacktrace (); } db = Connection.getdb ("one");//Get Database name}/** * Test create data document collection similar data table person * @throws unknownhostexcept        Ion * @throws Mongoexception */@Test public void Test1 () throws Unknownhostexception, Mongoexception { Instantiation of MongoDB MongoDB = new MongoDB("one");    Mongodb.createcollection ("person"); /** * Test adds a record * * @throws unknownhostexception * @throws mongoexception */@Test Public V        OID Test2 () throws Unknownhostexception, mongoexception {//instantiation dbobject p1 = new Basicdbobject ();        P1.put ("name", "zk00");    Insert (P1, "person"); /** * Test adds a record * * @throws unknownhostexception * @throws mongoexception */@Test Public V OID Test3 () throws Unknownhostexception, mongoexception {list<dbobject> dbobjects = new Arraylist<dbobjec        T> ();        DBObject ZS = new Basicdbobject ("name", "Zhaosi");        DBObject ZQ = new Basicdbobject ("name", "Zhuqi");        Dbobjects.add (ZS);        Dbobjects.add (ZQ);    Insertbatch (dbobjects, "person"); /** * Test Deletes a record by ID * * @throws unknownhostexception * @throws mongoexception */@Test PU Blic void Test4 () throws Unknownhostexception, Mongoexception {deletebyid ("553a5accb9d133bcf4056a40", "person");  /** * Test is deleted according to conditions * * @throws unknownhostexception * @throws mongoexception * */@Test public        void Test5 () throws Unknownhostexception, mongoexception {dbobject obj = new Basicdbobject ();        Obj.put ("name", "zk00");        int count = Deletebydbs (obj, "person");    System.out.println ("The number of bars to delete data is:" + count); /** * TEST Update operation * * @throws unknownhostexception * @throws mongoexception */@Test public VO        ID Test6 () throws Unknownhostexception, mongoexception {dbobject obj = new Basicdbobject ();        Obj.put ("name", "Zhaosi");        DBObject update = new Basicdbobject ();        Update.put ("$set", New Basicdbobject ("name", "Nn1"));    Update (obj, update, False, True, "person");     The/** * Test queries out the name in the person collection * * @throws unknownhostexception * @throws mongoexception */@Test public void Test7 () throws UnknownhosTexception, mongoexception {dbobject keys = new Basicdbobject ();        Keys.put ("_id", false);        Keys.put ("name", true);        dbcursor cursor = FIND (null, keys, "person");            while (Cursor.hasnext ()) {DBObject object = Cursor.next ();        System.out.println (Object.get ("name"));  }}/** * Test paging * * @throws unknownhostexception * @throws mongoexception */@Test public        void Test8 () throws Unknownhostexception, mongoexception {dbcursor cursor = find (null, NULL, 0, 6, "person");            while (Cursor.hasnext ()) {DBObject object = Cursor.next ();            System.out.print ("name=" + object.get ("name") + "");        System.out.println ("_id=" + object.get ("_id"));     }}/** * Create a Database collection * * @param collname * Collection name * @param DB * Database instance     */public void createcollection (String collname) {dbobject dbs = new Basicdbobject ();   Db.createcollection ("Person", DBS); /** * Add data to the corresponding collection * * @param DBS * @param collname */public void Insert (DBObject dbs, String        Collname) {//1. Get set Dbcollection coll = db.getcollection (collname);    2. Insert Operation Coll.insert (DBS); /** * BULK INSERT data for collection * * @param dbses * @param collname */public void Insertbatch (LIST&LT;DBOBJEC        T> dbses, String collname) {dbcollection coll = db.getcollection (collname);    Coll.insert (dbses); /** * Delete data by ID * * @param ID * @param collname * @return Returns the number of affected data bars */public int Deleteby        ID (string ID, string collname) {dbcollection coll = db.getcollection (collname);        DBObject dbs = new Basicdbobject ("_id", new ObjectId (ID));        int count = Coll.remove (DBS). GETN ();    return count; /** * Delete data based on condition * * @param ID * @param collname * @return Returns the number of affected data bars */public int Deleteby DbS (dbobject dbs, String collname) {dbcollection coll = db.getcollection (collname);        int count = Coll.remove (DBS). GETN ();    return count; }/** * Update data * * @param find * finder * @param update * Updater * @param up SERT * UPDATE or INSERT * @param multi * Whether bulk update * @param collname * Collection name * @ Return returns the number of data bars affected */public int update (DBObject find, DBObject Update, Boolean Upsert, Boolean multi, STR        ing collname) {dbcollection coll = db.getcollection (collname);        int count = coll.update (Find, Update, Upsert, multi). GETN ();    return count; }/** * Query (pagination) * @param ref * @param keys * @param start * @param limit * @return */Pub Lic dbcursor Find (dbobject ref, dbobject keys, int start, int limit, String collname) {Dbcursor cur = f        IND (ref, keys, collname); return Cur.limit (limit). Skip (start);    }/** * Query (no paging) * @param ref * @param keys * @param start * @param limit * @param collname * @return */public dbcursor find (dbobject ref, DBObject keys, String collname) {dbcollection coll = d        B.getcollection (Collname);        Dbcursor cur = coll.find (ref, keys);    return cur; }}

Note: Connection.close (); Do not forget to call, in addition to the Java students know the connection pool and release the issue of recycling links. MongoDB automatically implements the connection pool internally. You do not need to consider this issue again, or you can implement your own settings.

Java Operation MongoDB Implementation curd

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.