A simple example of the Java Operation MongoDB Database

Source: Internet
Author: User
Tags bulk insert

First import the MongoDB jar package Http://pan.baidu.com/s/1bnGMJRD

Database.java

Package com.mongodb.test;

Import java.net.UnknownHostException;

Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import Com.mongodb.Mongo;
Import com.mongodb.MongoException;
Import Com.mongodb.util.JSON;

public class DataBase {
public static void Main (string[] args)
Throws Unknownhostexception, Mongoexception {
1. Create a MONGO database connection object
Mongo mg = new Mongo ("127.0.0.1:27017");
Query all the database
For (String name:mg.getDatabaseNames ()) {
System.out.println ("DbName:" + name);
}
2. Create a connection to the related database
DB db = Mg.getdb ("Foobar");
Querying all collections of a database
For (String name:db.getCollectionNames ()) {
System.out.println ("CollectionName:" + name);
}

Dbcollection users = db.getcollection ("persons");
Querying all the data
Dbcursor cur = users.find ();
while (Cur.hasnext ()) {
DBObject object = Cur.next ();
System.out.println (Object.get ("name"));
}
System.out.println (Cur.count ());
System.out.println (Cur.getcursorid ());
System.out.println (json.serialize (cur));
}
}
Mongodb.java

Package com.mongodb.test;

Import java.net.UnknownHostException;
Import java.util.List;

Import Org.bson.types.ObjectId;

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;

public class MongoDb {
1. Create a MONGO database connection object
static Mongo connection = NULL;
2. Create a connection to the related database
static DB db = null;
Public MongoDb (String dbName) throws Unknownhostexception, mongoexception{
Connection = new Mongo ("127.0.0.1:27017");
db = Connection.getdb (dbName);
}
public static void Main (string[] args) throws Unknownhostexception, Mongoexception {
Instantiation of
MongoDB MongoDB = new MongoDB ("Foobar");
/**
* 1. Create a database named JAVADB
*/
Mongodb.createcollection ("javadb");
/**
* 2. Add a piece of data to the collection javadb
*/
DBObject dbs = new Basicdbobject ();
Dbs.put ("name", "uspcat.com");
Dbs.put ("Age", 2);
list<string> books = new Arraylist<string> ();
Books.add ("ExtJS");
Books.add ("MONGODB");
Dbs.put ("Books", books);
Mongodb.insert (DBS, "javadb");
/**
* 3. BULK INSERT Data
*/
list<dbobject> dbobjects = new arraylist<dbobject> ();
DBObject jim = new Basicdbobject ("name", "Jim");
DBObject lisi = new Basicdbobject ("name", "Lisi");
Dbobjects.add (Jim);
Dbobjects.add (Lisi);
Mongodb.insertbatch (dbobjects, "javadb");
/**
* 4. Delete data based on ID
*/
Mongodb.deletebyid ("502870dab9c368bf5b151a04", "javadb");
/**
* 5. Delete data based on criteria
*/
DBObject lisi = new Basicdbobject ();
Lisi.put ("name", "Lisi");
int count = Mongodb.deletebydbs (Lisi, "javadb");
System.out.println ("The number of strips of data deleted is:" +count);
/**
* 6. Update operation, add email properties to the collection
*/
DBObject update = new Basicdbobject ();
Update.put ("$set",
New Basicdbobject ("Eamil", "Test @126.com"));
Mongodb.update (New Basicdbobject (),
Update,false,true, "javadb");
/**
* 7. Query the name and age in the persons collection
*/
DBObject keys = new Basicdbobject ();
Keys.put ("_id", false);
Keys.put ("name", true);
Keys.put ("Age", true);
dbcursor cursor = Mongodb.find (null, keys, "persons");
while (Cursor.hasnext ()) {
DBObject object = Cursor.next ();
System.out.println (Object.get ("name"));
//     }
/**
* 7. Check out age is more than 26 years old and English score is less than 80
*/
DBObject ref = new Basicdbobject ();
Ref.put ("Age", New Basicdbobject ("$gte", 26));
Ref.put ("E", New Basicdbobject ("$lte", 80));
dbcursor cursor = Mongodb.find (ref, NULL, "persons");
while (Cursor.hasnext ()) {
DBObject object = Cursor.next ();
System.out.print (Object.get ("name") + "--");
System.out.print (Object.get ("age") + "--");
System.out.println (Object.get ("E"));
//     }
/**
* 8. Pagination Example
*/
dbcursor cursor = Mongodb.find (null, NULL, 0, 3, "persons");
while (Cursor.hasnext ()) {
DBObject object = Cursor.next ();
System.out.print (Object.get ("name") + "--");
System.out.print (Object.get ("age") + "--");
System.out.println (Object.get ("E"));
}
Close the Connection object
Connection.close ();
}
/**
* Wear pieces a database collection
* @param collname Collection name
* @param DB Database instance
*/
public void CreateCollection (String collname) {
DBObject dbs = new Basicdbobject ();
Db.createcollection ("Javadb", DBS);
}
/**
* Add data for the corresponding collection
* @param DBS
* @param collname
*/
public void Insert (DBObject dbs,string collname) {
1. Get the collection
Dbcollection coll = db.getcollection (collname);
2. Insert operation
Coll.insert (DBS);
}
/**
* Bulk INSERT data for collections
* @param dbses
* @param collname
*/
public void Insertbatch (list<dbobject> dbses,string collname) {
1. Get the collection
Dbcollection coll = db.getcollection (collname);
2. Insert operation
Coll.insert (dbses);
}
/**
* Delete data by ID
* @param ID
* @param collname
* @return Returns the number of data bars affected
*/
public int Deletebyid (String id,string collname) {
1. Get the collection
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 criteria
* @param ID
* @param collname
* @return Returns the number of data bars affected
*/
public int Deletebydbs (dbobject dbs,string collname) {
1. Get the collection
Dbcollection coll = db.getcollection (collname);
int count = Coll.remove (DBS). GETN ();
return count;
}
/**
* Update Data
* @param find Finder
* @param Update Updater
* @param upsert Update or insert
* @param multi whether batch update
* @param collname Collection name
* @return Returns the number of data bars affected
*/
public int update (DBObject find,
DBObject Update,
Boolean Upsert,
Boolean Multi,
String collname) {
1. Get the collection
Dbcollection coll = db.getcollection (collname);
int count = coll.update (Find, Update, Upsert, multi). GETN ();
return count;
}
/**
* Finder (paging)
* @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);
}
/**
* Finder (no paging)
* @param ref
* @param keys
* @param start
* @param limit
* @param collname
* @return
*/
Public dbcursor Find (dbobject ref,
DBObject Keys,
String collname) {
1. Get the collection
Dbcollection coll = db.getcollection (collname);
Dbcursor cur = coll.find (ref, keys);
return cur;
}
}

Java operating a simple instance of the MongoDB database

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.