Implement CURD using mongoDB in java

Source: Internet
Author: User

Implement CURD using mongoDB in java

Java operations on mongoDB
MongoDB, as a cool nosql memory database, does have many advantages. MongoDB can handle Internet applications with large data volumes, high concurrency, and weak transactions. When I came into contact with mongoDB, I referred to the following api to implement addition, deletion, modification, and query. mongoDB is an object-oriented design and can be implemented without the need to write SQL statements and directly operate on api methods, we are blessed with poor database statement writing. 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. except exception;/*** test mongodb curd * @ author zk * @ time 23:19:15 on January 1, April 24, 2015 */public class DataTest {// 1. create a Mongo database connection object static Mongo connection = null; // 2. create a connection to the relevant 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 "); // obtain the database name}/*** Test the creation of a data document set similar to the data table person * @ throws UnknownHostException * @ throws unknown exception */@ Test public void test1 () throws UnknownHostException, except exception {// instantiate MongoDb mongoDb = new MongoDb ("one"); mongoDb. createCollection ("person");}/*** Test adding a record ** @ throws UnknownHostException * @ throws unknown exception */@ Test public void test2 () throws UnknownHostException, export exception {// instantiate DBObject p1 = new BasicDBObject (); p1.put ("name", "zk00"); insert (p1, "person ");} /*** Add a record ** @ throws UnknownHostException * @ throws unknown exception */@ Test public void test3 () throws UnknownHostException, unknown exception {List
  
   
DbObjects = new ArrayList
   
    
(); DBObject zs = new BasicDBObject ("name", "zhaosi"); DBObject zq = new BasicDBObject ("name", "zhuqi"); dbObjects. add (zs); dbObjects. add (zq); insertBatch (dbObjects, "person ");} /*** Test the deletion of a record by id ** @ throws UnknownHostException * @ throws unknown exception */@ Test public void test4 () throws UnknownHostException, except exception {deleteById ("unknown ", "person");}/*** Test deletion based on conditions ** @ throws UnknownHostException * @ throws unknown exception */@ Test public void test5 () throws UnknownHostException, export exception {DBObject obj = new BasicDBObject (); obj. put ("name", "zk00"); int count = deleteByDbs (obj, "person"); System. out. println ("the number of deleted data entries is:" + count);}/*** Test the update operation ** @ throws UnknownHostException * @ throws unknown exception */@ Test public void test6 () throws UnknownHostException, writable exception {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 name ** @ throws UnknownHostException * @ throws unknown exception */@ Test public void test7 () throws UnknownHostException in the person set is queried, except exception {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 page ** @ throws UnknownHostException * @ throws unknown exception */@ Test public void test8 () throws UnknownHostException, parse exception {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 set ** @ param collName * Set name * @ param db * database instance */public void createCollection (String collName) {DBObject dbs = new BasicDBObject (); db. createCollection ("person", dbs);}/*** add data to the corresponding set ** @ param dbs * @ param collName */public void insert (DBObject dbs, string collName) {// 1. obtain the collection DBCollection coll = db. getCollection (collName); // 2. insert operation coll. insert (dbs);}/*** insert data in batches for the set ** @ param dbses * @ param collName */public void insertBatch (List
    
     
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 entries */public int deleteById (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 conditions ** @ param id * @ param collName * @ return returns the number of affected data entries */public int deleteByDbs (DBObject dbs, String collName) {DBCollection coll = db. getCollection (collName); int count = coll. remove (dbs ). getN (); return count ;} /***** update data ** @ param find * queryer * @ param update * Updater * @ param upsert * update or insert * @ param multi * batch update * @ param collName * Set name * @ return returns the number of affected data entries */public int update (DBObject find, DBObject update, boolean upsert, boolean multi, String 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 */public DBCursor find (DBObject ref, DBObject keys, int start, int limit, String collName) {DBCursor cur = find (ref, keys, collName); return cur. limit (limit ). skip (start);}/*** query (not paging) * @ param ref * @ param keys * @ param start * @ param limit * @ param collName * @ return */public DBCursor find (DBObject ref, DBObject keys, String collName) {DBCollection coll = db. getCollection (collName); DBCursor cur = coll. find (ref, keys); return cur ;}}
    
   
  

Note: connection. close (); Do not forget to call it. Other students who have done java know the connection pool and release the recycle link. Mongodb automatically implements the connection pool internally. You do not need to consider this issue, or you can set it yourself.

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.