Tutorial on adding, deleting, modifying, and querying instances using MongoDB in Java

Source: Internet
Author: User
Tags mongodb

Now we use Java to operate MongoDB data.

I. Preparations

1. First, download the driver packages supported by mongoDB for Java.

Driver Package download address: https://github.com/mongodb/mongo-java-driver/downloads

MongoDB Java-related support, technology: http://www.mongodb.org/display/DOCS/Java+Language+Center

Driver Source Code Download: https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip

Source code: https://github.com/mongodb/mongo-java-driver

2. Create a JavaProject project to import the downloaded driver package. You can use mongoDB in Java. The directory is as follows:

 

II. Java MongoDB operation example

Before this example, you can start the mongod.exe service. After the service is started, the following program can be successfully executed;

1. Create SimpleTest. java to complete simple mongoDB database operations

Mongo mongo = new Mongo ();

In this way, a MongoDB database connection object is created, which is connected to the localhost address of the current machine by default, and the port is 27017.

DB db = mongo. getDB ("test ");

In this way, a database named test is obtained. If this database is not created in mongoDB, it can run normally. If you have read the previous article, you will know that mongoDB can add data without creating this database. When this database is not added, mongoDB automatically creates the current database.

After obtaining the db, we will get a "clustered collection DBCollection" and use the getCollection method of the db object.

DBCollection users = db. getCollection ("users ");

In this way, a DBCollection is obtained, which is equivalent to the "table" of our database ".

Query all data

 

The code is as follows: Copy code
DBCursor cur = users. find ();
While (cur. hasNext ()){
System. out. println (cur. next ());
}

 

Complete source code

 

The code is as follows: Copy code

Package com. hoo. test;

Import java.net. UnknownHostException;

Import com. mongodb. DB;

Import com. mongodb. DBCollection;

Import com. mongodb. DBCursor;

Import com. mongodb. Mongo;

Import com. mongodb. Parse exception;

Import com. mongodb. util. JSON;

Public class SimpleTest {

Public static void main (String [] args) throws UnknownHostException, except exception {

Mongo mg = new Mongo ();

// Query all databases

For (String name: mg. getDatabaseNames ()){

System. out. println ("dbName:" + name );

        }

       

DB db = mg. getDB ("test ");

// Query all clustering sets

For (String name: db. getCollectionNames ()){

System. out. println ("collectionName:" + name );

        }

DBCollection users = db. getCollection ("users ");

// Query all data

DBCursor cur = users. find ();

While (cur. hasNext ()){

System. out. println (cur. next ());

        }

System. out. println (cur. count ());

System. out. println (cur. getCursorId ());

System. out. println (JSON. serialize (cur ));

    }

}

 

2. To complete the CRUD operation, first create MongoDB4CRUDTest. java. The basic test code is as follows:

 

The code is as follows: Copy code

Package com. hoo. test;

Import java.net. UnknownHostException;

Import java. util. ArrayList;

Import java. util. List;

Import org. bson. types. ObjectId;

Import org. junit. After;

Import org. junit. Before;

Import org. junit. Test;

Import com. mongodb. BasicDBObject;

Import com. mongodb. Bytes;

Import com. mongodb. DB;

Import com. mongodb. DBCollection;

Import com. mongodb. DBCursor;

Import com. mongodb. DBObject;

Import com. mongodb. Mongo;

Import com. mongodb. Parse exception;

Import com. mongodb. QueryOperators;

Import com. mongodb. util. JSON;

Public class MongoDB4CRUDTest {

   

Private Mongo mg = null;

Private DB;

Private DBCollection users;

   

@ Before

Public void init (){

Try {

Mg = new Mongo ();

// Mg = new Mongo ("localhost", 27017 );

} Catch (UnknownHostException e ){

E. printStackTrace ();

} Catch (except Exception e ){

E. printStackTrace ();

        }

// Obtain temp DB. If no temp DB is created by default, mongodb will automatically create

Db = mg. getDB ("temp ");

// Obtain the users DBCollection. If it is not created by default, mongodb will automatically create

Users = db. getCollection ("users ");

    }

   

@ After

Public void destory (){

If (mg! = Null)

Mg. close ();

Mg = null;

Db = null;

Users = null;

System. gc ();

    }

   

Public void print (Object o ){

System. out. println (o );

    }

}

 

3. ADD operation

Before adding an operation, we need to write a query method to query all the data. The code is as follows:

 

The code is as follows: Copy code

Private void queryAll (){

Print ("query all users data :");

// Db cursor

DBCursor cur = users. find ();

While (cur. hasNext ()){

Print (cur. next ());

    }

}

@ Test

Public void add (){

// Query all data first

QueryAll ();

Print ("count:" + users. count ());

   

DBObject user = new BasicDBObject ();

User. put ("name", "hoojo ");

User. put ("age", 24 );

// Users. save (user) save, getN () get the number of affected rows

// Print (users. save (user). getN ());

   

// Expand the field and add the field without affecting the existing data.

User. put ("sex", "male ");

Print (users. save (user). getN ());

   

// Add multiple data entries and pass the Array object

Print (users. insert (user, new BasicDBObject ("name", "tom"). getN ());

   

// Add a List set

List <DBObject> list = new ArrayList <DBObject> ();

List. add (user );

DBObject user2 = new BasicDBObject ("name", "lucy ");

User. put ("age", 22 );

List. add (user2 );

// Add a List set

Print (users. insert (list). getN ());

   

// Query the data to see if the data is successfully added.

Print ("count:" + users. count ());

QueryAll ();

}

 

4. Delete data

 

The code is as follows: Copy code

@ Test

Public void remove (){

QueryAll ();

Print ("delete id = 4de73f7acd812d61b4626a77:" + users. remove (
New BasicDBObject ("_ id", new ObjectId ("4de73f7acd812d61b4626a77"). getN ());

Print ("remove age> = 24:" + users. remove (
New BasicDBObject ("age", new BasicDBObject ("$ gte", 24). getN ());

}

 

5. Modify data

 

The code is as follows: Copy code

@ Test

Public void modify (){

Print ("modify:" + users. update (new BasicDBObject ("_ id ",
New ObjectId ("4dde25d06be7c53ffbd70906"), new BasicDBObject ("age", 99). getN ());

Print ("modify:" + users. update (

New BasicDBObject ("_ id ",
New ObjectId ("4dde2b06feb038463ff09042 ")),

New BasicDBObject ("age", 121 ),

True, // if the database does not exist, add

False // multiple modifications

). GetN ());

Print ("modify:" + users. update (

New BasicDBObject ("name", "haha "),

New BasicDBObject ("name", "dingding "),

True, // if the database does not exist, add

True // false: only the first day is modified. true: if there are multiple entries, it is not modified.

). GetN ());

   

// When the database does not exist, it does not modify or add data, but does not modify multiple data entries.

}

 

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.