Java Operation MongoDB

Source: Internet
Author: User
Tags bulk insert findone mongoclient

Code Listing 1:

 PackageCom.ooooo.mongo;Importjava.net.UnknownHostException;ImportJava.util.Set;ImportOrg.json.JSONArray;Importorg.json.JSONException;ImportOrg.json.JSONObject;Importorg.junit.Test;ImportCom.mongodb.BasicDBObject;ImportCom.mongodb.DB;Importcom.mongodb.DBCollection;ImportCom.mongodb.DBCursor;Importcom.mongodb.MongoClient;Importcom.mongodb.MongoException; Public classJavamongodbtest {/*** Java + MongoDB Hello World example**/     Public Static voidMain (string[] args) {Try {           //instantiating a Mongo object, connecting 27017 portsMongoclient MONGO =NewMongoclient ("localhost", 27017); //connect a database named Yourdb, if the database does not exist, MongoDB will automatically establishDB db = Mongo.getdb ("Ytn-db"); //Get collection from MongoDB, database named "Yourdb"//A collection of data named Yourcolleection is obtained from MongoDB, and if the data collection does not exist, MongoDB creates a newDbcollection collection = Db.getcollection ("Yourcollection"); //use the Basicdbobject object to create a MongoDB document and give the assignment. Basicdbobject document =NewBasicdbobject (); Document.put ("id", 1002); Document.put ("MSG", "Hello World MongoDB in Java---ytan"); Document.put ("Msg23", "Hello World MongoDB in Java---yian--002"); Document.put ("msg23111", "Hello World MongoDB in Java---yun--002"); //Save the newly created document to the collectionCollection.insert (document); //create the document to queryBasicdbobject SearchQuery =NewBasicdbobject (); Searchquery.put ("id", 1002); //Find document Using Collection's Find methoddbcursor cursor =Collection.find (searchQuery); //Loop Output Results            while(Cursor.hasnext ()) {System.out.println (Cursor.next ()); } System.out.println ("Done"); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(mongoexception e) {e.printstacktrace (); }} @Test Public voidTestcase01_mongodb2json ()throwsException {//instantiating a Mongo object, connecting 27017 portsMongoclient MONGO =NewMongoclient ("localhost", 27017); //connect a database named Yourdb, if the database does not exist, MongoDB will automatically establish             for(String s:mongo.getdatabasenames ()) {System.out.println (s); } DB DB= Mongo.getdb ("Ynt-db"); Set<String> collections =Db.getcollectionnames ();  for(String collectionname:collections) {System.out.println (CollectionName); }                      //Get collection from MongoDB, database named "Yourdb"//A collection of data named Yourcolleection is obtained from MongoDB, and if the data collection does not exist, MongoDB creates a newDbcollection collection = Db.getcollection ("Yourcollection"); Basicdbobject SearchQuery=NewBasicdbobject (); Searchquery.put ("id", 1002); //Find document Using Collection's Find methoddbcursor cursor =Collection.find (searchQuery); Jsonobject Datajson=NewJsonobject (string.valueof (Cursor.next ()));   System.out.println (Datajson); //jsonobject response=datajson.getjsonobject ("msg");//Jsonarray Data=response.getjsonarray ("data");//Jsonobject info=data.getjsonobject (0);String province=datajson.getstring ("MSG"); String City=datajson.getstring ("id"); String District=datajson.getstring ("_id"); System.out.println (province+city+district); }}

MongoDB MONGO

using MONGODB requires importing the following classes, of course not all needed, and the classes used are imported. ImportCom.mongodb.Mongo; ImportCom.mongodb.DB; Importcom.mongodb.DBCollection; ImportCom.mongodb.BasicDBObject; ImportCom.mongodb.DBObject; ImportCom.mongodb.DBCursor; Importcom.mongodb.ObjectId;  Class conversion When a class object is stored in MongoDB, it is removed from MongoDB using Setobjectclass () to convert it back to its original class.  Public classTweetsImplementsDBObject {/* ... */} Tweet Mytweet=NewTweet (); Mytweet.put ("User", "Bruce"); Mytweet.put ("Message", "Fun"); Mytweet.put ("Date",NewDate ());  Collection.insert (Mytweet); //ConversionCollection.setobjectclass (Tweet); Tweet Mytweet=(Tweet) Collection.findone (); Default ID when the saved object has no set ID, MongoDB defaults to the record setting an ID ("_ID"). Of course you can also set your own specified ID, such as: (Executed in MongoDB with Db.users.save ({_id:1,name: ' Bruce '});) Basicdbobject Bo=NewBasicdbobject (); Bo.put (' _id ', 1); Bo.put (' Name ', ' Bruce ');  Collection.insert (BO);  Permission to determine if there is mongodb access, there is a return true, otherwise return false. BooleanAuth =db.authenticate (MyUserName, MyPassword); View MongoDB Database list Mongo m=NewMongo ();  for(String s:m.getdatabasenames ()) {System.out.println (s);  } View all the table names under the current library, equal to execute show tables in MongoDB; Set<String> Colls =Db.getcollectionnames ();  for(String s:colls) {System.out.println (s); View the index of a table list<DBObject> list =Coll.getindexinfo ();  for(DBObject o:list) {System.out.println (o); Delete a database Mongo m=NewMongo (); M.dropdatabase ("MyDatabaseName"); Create a MongoDB link Mongo m=NewMongo ("localhost", 27017); DB DB= M.getdb ("MyDatabaseName");//equivalent to the library nameDbcollection coll = db.getcollection ("myuserstable");//equivalent to table name#查询数据 Query The first record dbobject Firstdoc=Coll.findone ();  FindOne () returns a record, and find () returns the Dbcursor cursor object. Query all data dbcursor cur=Coll.find ();  while(Cur.hasnext ()) {System.out.println (Cur.next ());  The number of query Records Coll.find (). Count (); Coll.find (NewBasicdbobject ("Age", 26) . Count (); Set up a conditional query basicdbobject condition=NewBasicdbobject (); Condition.put ("Name", "Bruce"); Condition.put ("Age", 26);  Coll.find (condition); Querying part of the data block dbcursor cursor= Coll.find (). Skip (0). Limit (10);  while(Cursor.hasnext ()) {System.out.println (Cursor.next ()); } comparison query ( age> 50) basicdbobject Condition=NewBasicdbobject (); Condition.put ("Age",NewBasicdbobject ("$gt", 50));  Coll.find (condition); Comparison characters"$gt": Greater than"$gte": Greater than or equal to"$lt": Less than"$lte": Less than or equal to"$in": Contains//the following conditions query 20<age<=30Condition.put ("Age",NewBasicdbobject ("$gt"). Append ("$lte", 30)); #插入数据 BULK Insert List datas=NewArrayList ();  for(inti=0; I < 100; i++) {basicdbobject bo=NewBasicdbobject (); Bo.put ("Name", "Bruce"); Bo.append ("Age", i);  Datas.add (BO);  } coll.insert (Datas); Regular expression query all names match/joh?n/I's record pattern pattern= Pattern.compile ("Joh?n", case_insensitive); Basicdbobject Query=NewBasicdbobject ("name", pattern); Dbcursor cursor= Coll.find (query);

Java Operation MongoDB

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.