Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
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.MongoClient;
Import com.mongodb.MongoException;
Import com.mongodb.QueryOperators;
Import com.mongodb.ReadPreference;
Import com.mongodb.ServerAddress;
Import Com.mongodb.gridfs.GridFS;
Import Com.mongodb.gridfs.GridFSDBFile;
Import Com.mongodb.gridfs.GridFSInputFile;
Import Com.mongodb.util.JSON; /** * @Title: Mongodb.java * @Package * @Description: TODO (describe what the file does in a word) * @author Onyx * * @date 2013-1-17 afternoon 05:0 0:20 */* * @ClassName: MongoDB * @Description: TODO (Describe the role of this class in one sentence) * @author Onyx only * @date 2013-1-17 afternoon 05:00:20 * * * @Sup
Presswarnings ("deprecation") public class MongoDB {private Mongo mg = null;
private DB DB;
Private dbcollection users;
public static void Main (string[] args) {try{//database file location depends on the location specified at the Mongo service startup Mongo Mongo = new Mongo (); Query all database for (String name:mongo.getDatabaseNames ()) {System.out.println ("dbname:" + name)
;
}//Connection specified database db db = Mongo.getdb ("Copytest"); Queries all clustered collections (querying all tables under the Copytest Library) for (String Name:db.getCollectionNames ()) {System.out.println ("coll
Ectionname: "+ name);
}//Connection specified table (set) dbcollection testcollection = db.getcollection ("foo");
Dbcursor cur = testcollection.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));
}catch (Exception e) {System.out.println (e);
@Before public void Init () {try {mg = new Mongo ();
MG = new Mongo ("localhost", 27017);
catch (Unknownhostexception e) {e.printstacktrace ();
catch (Mongoexception e) {e.printstacktrace ();
//Get temp db; If not created by default, MongoDB will automatically create DB = Mg.getdb ("temp");
Get the users dbcollection; if not created by default, MongoDB automatically creates users = Db.getcollection ("users"); /** * <b>function:</b> Query all data * @author Hoojo * @createDate 2011-6-2 PM 03:22:40/@Test Public
void Queryall () {print ("Query all data for users:");
DB cursor Dbcursor cur = users.find ();
while (Cur.hasnext ()) {print (Cur.next ());
@Test public void Add () {//First query all data Queryall ();
Print ("Count:" + users.count ());
DBObject user = new Basicdbobject (); UseR.put ("name", "Hoojo2");
User.put ("Age", 242);
Users.save (user),//Save, GETN () Gets the number of rows that affect print (Users.save (). GETN ());
Expand Fields, add fields at will, and do not affect existing data user.put ("Sex", "male");
Print (Users.save (user). GETN ());
Add multiple data, passing the Array object print (Users.insert (user, new Basicdbobject ("name", "Tom")). GETN ());
Add list list<dbobject> list = new arraylist<dbobject> ();
List.add (user);
DBObject user2 = new Basicdbobject ("name", "Lucy");
User.put ("Age", 22);
List.add (User2);
Add the List collection print (Users.insert (list). GETN ());
Query the data to see if the Add success print ("Count:" + users.count ());
Queryall ();
@Test public void Remove () {Queryall (); Print (Delete id = 4de73f7acd812d61b4626a77:) + users.remove (new Basicdbobject ("_id", New ObjectId ("
4de73f7acd812d61b4626a77 ")). GETN ());
Print ("Remove Age >=:" + users.remove (New Basicdbobject ("Age", New Basicdbobject ("$gte")). GETN ()); } @Test
public void Modify () {print ("Modify:" + users.update (New Basicdbobject ("_id", New ObjectId ("4dde25d06be7c53ffbd70906")
), New Basicdbobject ("Age"). GETN ());
Print ("Modify:" + users.update (New Basicdbobject ("_id", New ObjectId ("4dde2b06feb038463ff09042")),
New Basicdbobject ("age", 121), true,//add false//multiple modifications if the database does not exist. GETN ()); Print ("Modify:" + users.update (new Basicdbobject ("name", "haha"), new Basicdbobject ("name", "Dingd
ing "), true,//if the database does not exist, add true//false to modify the first day only, true if there are more than one. GETN ()); When the database does not exist, do not modify, do not add data, when more than one data is not modified//print ("Modify multiple:" + coll.updatemulti (New Basicdbobject ("_id", New ObjectId ("4dde23616be7
c19df07db42c ")), new Basicdbobject (" name "," 199 ")); //MONGODB does not support federated queries, subqueries, which require ourselves to complete in the program.
The result set of the query is filtered in the Java query as needed.
@Test public void query () {//query for All//queryall ();
Query id = 4de73f7acd812d61b4626a77 Print ("Find id = 4de73f7acd812d61b4626a77:" + users.find (New Basicdbobject ("_id", New ObjectId ("4de73f7acd812d61b4626
A77 ")). ToArray ());
Query age = Print (' Find age =: ' + users.find (new Basicdbobject ("Age"). ToArray ());
Force the use of an index//users.sethintfields (LST); Query Age >= Print ("Discovery Age >=:" + users.find (New Basicdbobject (' age ', New Basicdbobject ("$gte")). To
Array ());
Print ("Find age <=:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$lte")). ToArray ());
Print ("Query age!=25:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$ne")). ToArray ()); Print (query age in 25/26/27:) + users.find (New Basicdbobject ("Age", New Basicdbobject (queryoperators.in, new int[] {25, 26,
)). ToArray ()); Print (query age isn't in 25/26/27: + users.find (New Basicdbobject ("Age", New Basicdbobject (Queryoperators.nin, new int[] {25,
)). ToArray ()); Print ("Query Age exists sort:" + users.fIND (New Basicdbobject ("Age", New Basicdbobject (Queryoperators.exists, True)). ToArray ());
Print (query Age property only: + Users.find (NULL, New Basicdbobject ("Age", true)). ToArray ());
Print ("Check attributes only:" + users.find (null, New Basicdbobject ("Age", true), 0, 2). ToArray ());
Print ("Check attributes only:" + users.find (null, New Basicdbobject ("Age", true), 0, 2, bytes.queryoption_notimeout). ToArray ());
Query only one piece of data, many go to the first print ("FindOne:" + users.findone ());
Print ("FindOne:" + users.findone (New Basicdbobject ("Age", 26));
Print ("FindOne:" + users.findone (New Basicdbobject ("Age"), new Basicdbobject ("name", true));
Query modification, delete print ("Findandremove query age=25 data, and delete:" + users.findandremove (New Basicdbobject ("Age", 25)); Queries age=26 data and modifies the value of name to ABC print ("Findandmodify:" + users.findandmodify (New Basicdbobject ("Age"), new basicdbo
Bject ("name", "ABC")); Print ("findandmodify:" + users.findandmodify (New Basicdbobject ("Age", 28),///query age=28 data new Basicdbobject ("name", true),//Query Name property new Basicdbobject ("Age", true),//Sort by age False,//delete, true to delete new Basicdbobject ("name", "ABC"),//modified value, modify name to ABC true, true
);
Queryall ();
@Test public void Testothers () {dbobject user = new Basicdbobject ();
User.put ("name", "Hoojo");
User.put ("Age", 24);
JSON Object converts print ("Serialize:" + json.serialize (user));
Deserialization print ("Parse:" + json.parse ("{\ name\": \ "hoojo\", \ "age\": 24}));
Print ("Judge if temp collection exists:" + db.collectionexists ("temp"));
If not present, create if (!db.collectionexists ("temp")) {dbobject options = new Basicdbobject ();
Options.put ("size", 20);
Options.put ("capped", 20);
Options.put ("Max", 20);
Print (Db.createcollection ("Account", options));
//Set DB to read-only db.setreadonly (true); Read-only cannot writeData db.getcollection ("Test"). Save (user);
@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);
@Test public void SavePicture () {try{//if not, automatically create db db = Mg.getdb ("Beijingvector");
Dbcollection collection = Db.getcollection ("Beijingvector");
Gridfs gridfs= New Gridfs (db); Gridfsinputfile GFs = gridfs.createfile (new FileInputStream ("e:\\ tile data \ beijing Image \\L11\\R000002fc\\C0000069b.jpg
")));
Gfs.put ("filename", "aaaaaaaaaaa");
Gfs.save ();
}catch (Exception e) {//Todo:handle Exception}} @Test public void Getpicturebyname () {try{
If not, automatically create db db = Mg.getdb ("Beijingvector");
Gridfs gridfs= New Gridfs (db);
/*dbobject query = new Basicdbobject ("filename", filename); Gridfsdbfile GRIDFSDBFile = myfs.findone (query);
Query by id dbobject query = new Basicdbobject ("_id", id); Gridfsdbfile gridfsdbfile = myfs.findone (query);/gridfsdbfile gridfsdbfile = Gridfs.findone ("aaaaaaaaaaa");
directly query its filename gridfsdbfile.writeto ("c:\test.png");
InputStream is = Gridfsdbfile.getinputstream ();
int buffer_size = 1024;
FileOutputStream fos = new FileOutputStream (New File ("C:\\cc.png"));
Final byte[] B = new Byte[buffer_size];
int read;
while (read = Is.read (b))!=-1) {fos.write (b, 0, read);
} is.close ();
Fos.flush ();
Fos.close ();
if (gridfsdbfile!= null) return;
The}catch (Exception e) {}}//is saved in binary mode @Test public void Savepicbydoc () {try{
If not, automatically create db db = Mg.getdb ("Beijingvector");
Dbcollection collection = Db.getcollection ("Beijingvector");
InputStream is = new FileInputStream (New File ("e:\\ tile data \ Beijing image \\L11\\R000002fc\\C0000069b.jpg"); BytearRayoutputstream output = new Bytearrayoutputstream ();
byte[] buffer = new byte[4096];
int n = 0;
while ( -1!= (n = is.read (buffer)) {output.write (buffer, 0, N);
} byte[] Imgbyte = Output.tobytearray ();
DBObject user = new Basicdbobject ();
User.put ("name", "AA");
User.put ("img", Imgbyte);
Collection.save (user);
BULK Insert//collection.insert (list);
}catch (Exception e) {//Todo:handle Exception}} @Test public void Getpicfrombyte () {try{
If not, automatically create db db = Mg.getdb ("Beijingvector");
Dbcollection collection = Db.getcollection ("Beijingvector");
list<dbobject> list = Collection.find (new Basicdbobject ("name", "AA")). ToArray ();
if (list!= null&& list.size () > 0) {byte[] b = (byte[)) list.get (0). Get ("img");
Bytearrayinputstream bas = new Bytearrayinputstream (b); FileOutputStream fos =New FileOutputStream (New File ("C:\\a.png"));
Fos.write (b, 0, b.length);
Fos.flush ();
Fos.close (); }catch (Exception e) {}}/** * * @Title: Ensureindex * @Params: * @Descript Ion:todo (CREATE INDEX) * @return void return type * @author Onyx * @throws/@Test public void Ensureind
Ex () {try{//if not, automatically create db db = Mg.getdb ("Beijingvector");
Dbcollection collection = Db.getcollection ("Beijingvector");
Single-segment index Collection.ensureindex (new Basicdbobject ("name", 1), "Nameindex", true);
Compound index Basicdbobject obj = new Basicdbobject ();
Obj.put ("Age", 1);//Ascending Obj.put ("Name",-1);//Descending collection.ensureindex (obj);
list<dbobject> list = Collection.getindexinfo ();
for (DBObject o:list) {System.out.println (o); }catch (Exception e) {}}/** * @Title: Configuring Master-SlaveCluster (master-slave replication) * @Params: * @Description: TODO (when testing, do not add data to the default local collection, otherwise you will not see the effect, the default is the data in different steps local) * @return void return type * @author Onyx * @throws * * @Test public void Adddatatomaster () throws Unknownhostexception
{{Mongoclient mongoclient = new Mongoclient (new ServerAddress ("localhost", 1000);
DB db = Mongoclient.getdb ("Testmasterdb");
Dbcollection collection = Db.getcollection ("testmastercollection");
DBObject dbobject = new Basicdbobject ();
Dbobject.put ("name", "Test Force 4");
Collection.save (DBObject);
dbcursor cursor = Collection.find ();
while (Cursor.hasnext ()) {DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
} mongoclient.close (); }//system default 10s sync once, so the following code to be executed in 10 seconds, please directly in Mongovue to see the effect of {mongoclient mongoclient = new Mongoclient (
New ServerAddress ("localhost", 10002));
DB db = Mongoclient.getdb ("Testmasterdb"); DbCollection Collection = db.getcollection ("testmastercollection");
dbcursor cursor = Collection.find ();
while (Cursor.hasnext ()) {DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
} mongoclient.close (); }/** * @Title: Configure replica Sets (data can be automatically replicated between active and backup nodes) * @Params: * @Description: TODO () * @return V OID return type * @author Onyx * @throws * * @Test public void Adddatatoreplset () throws Unknownhostexcep tion{{//Cannot connect inactive nodes for unknown reason, Shell can only connect, cannot insert data, report not master error mongoclient mongoclient = new Mongoclient (New S
Erveraddress ("localhost", 10001));
Set the secondary node readable, in the secondary inside also need to do the following setting Mongoclient.setreadpreference (Readpreference.secondarypreferred ());
DB db = Mongoclient.getdb ("Testreplsetdb");
Dbcollection collection = Db.getcollection ("testreplsetcollection");
DBObject dbobject = new Basicdbobject (); Dbobject.put ("name", "ETRHGWText for me too re ");
Collection.save (DBObject);
dbcursor cursor = Collection.find ();
while (Cursor.hasnext ()) {DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
} mongoclient.close ();
{Mongoclient mongoclient = new Mongoclient (new ServerAddress ("localhost", 10002));
Mongoclient.setreadpreference (readpreference.secondarypreferred ());
DB db = Mongoclient.getdb ("Testreplsetdb");
Dbcollection collection = Db.getcollection ("testreplsetcollection");
dbcursor cursor = Collection.find ();
while (Cursor.hasnext ()) {DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
} mongoclient.close ();
}
}
}