Example:Package com.sdfwerwer.test;
Import java.net.UnknownHostException;
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;
/**
* MongoDB Curd Test
*
* Author:svennee
*/
public class Testmongodb {
public static void Main (string[] args) {
try {
/**
* Connection MongoDB
*/
/*
* Mongoobject has a constructor (String, int)
*
* String = host:127.0.0.1 (default value) or 192.168.1.155
* int = port:27017 (default value)
*/
Mongo Mongo = new Mongo ("192.168.1.161", 27017);
DB db = Mongo.getdb ("N_db_test");
Dbcollection City = db.getcollection ("city");
/**
* Insert Data
*/
Basicdbobject needaddobject = new Basicdbobject ();
Needaddobject.put ("CID", "c001");
Needaddobject.put ("City_name", "Wuhan");
Needaddobject.put ("Country", "Hubei");
City.insert (Needaddobject);
System.out.println ("Insert data success~");
/**
* Read Data
*/
Basicdbobject querycondition = new Basicdbobject ();
Querycondition.put ("City_name", "Wuhan");
Dbcursor querycursor = City.find (querycondition);
Dbcursor queryallcursor = City.find ();
while (Querycursor.hasnext ()) {
SYSTEM.OUT.PRINTLN ("Read Condition Data:" +querycursor.hashcode () + "ReadValue:" + querycursor.next ());
}
while (Queryallcursor.hasnext ()) {
System.out.println ("Read All Data:" +queryallcursor.hashcode () + "ReadValue:" + queryallcursor.next ());
}
System.out.println ("Read data success~");
/**
* Modify Data
*/
One method (this is more powerful!) )
Basicdbobject needmodifydata = new Basicdbobject ();
Needmodifydata.put ("CID", "c001");
Dbcursor modifycursor = City.find (Needmodifydata);
if (Modifycursor.hasnext ()) {
DBObject modifyobject = Modifycursor.next ();
Modifyobject.put ("CID", "c002");
City.save (Modifyobject);
}
The method
Basicdbobject old_val = new Basicdbobject (), new_val = new Basicdbobject ();
Old_val.put ("City_name", "Wuhan");
New_val.put ("City_name", "Wuhan Suzhou");
City.update (Old_val, new_val);
System.out.println ("modfiy data success~");
/**
* Delete Data
*/
Basicdbobject needdeldata = new Basicdbobject ();
Needdeldata.put ("City_name", "Wuhan Suzhou");
Dbcursor delcursor = City.find (Needdeldata);
while (Delcursor.hasnext ()) {
DBObject delobject = Delcursor.next ();
City.remove (Delobject);
}
System.out.println ("Delete data success~");
} catch (Unknownhostexception e) {
System.err.println ("Unknownhostexception");
E.printstacktrace ();
} catch (Mongoexception e) {
System.err.println ("Mongoexception");
E.printstacktrace ();
}
}
}
MongoDB Java SDK CRUD Operations Example