Java uses MongoDB

Source: Internet
Author: User
Tags mongoclient

1. Connect your MongoDB First

See if there is a problem with the connection, code

public class MongoDB2 {private static mongodatabase mongodatabase = null;private static int port = 27017;private static St Ring UserName = "XX";p rivate static string password= "XX";p rivate static string database = "GATP";p rivate static string ho  St= "XXX";/** * MONGO DB connection * * */public void Mongoconnect () {try {//host and port for conversion encryptiondecryption decryption = new Encryptiondecryption (); ServerAddress serveraddress = new ServerAddress (host, Port); list<serveraddress> addresses = new arraylist<serveraddress> (); Addresses.add (serveraddress); Mongocredential credential = mongocredential.createcredential (Username,database, Password.tochararray ()); List<mongocredential> credentials = new arraylist<mongocredential> (); Credentials.add (credential);// Get MongoDB connection via connection authentication mongoclient mongoclient = new Mongoclient (addresses, credentials); mongodatabase = Mongoclient.getdatabase (database); Log.loginfo (mongodatabase);} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();}}public static void Main (string[] args) {MongoDB2 db=new MongoDB2 ();d b.mongoconnect ();//Confirm connection is correct} 

The Mogodb ID will be displayed when the connection is successful, and the error will show the authentication failure

Case of connection failure

Success will show

2. Inserting data into the MOGODB

encapsulates the method insertcollection, inserting a numeric, string,

public boolean insertcollection (String CollectionName, list<document> documents) {Boolean insertresult = false; Try {mongocollection<document> collection = mongodatabase.getcollection (CollectionName); Collection.insertmany (documents); insertresult = true;} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();} return insertresult;}    public static void Main (string[] args) {MongoDB2 db=new MongoDB2 ();d b.mongoconnect ();//Verify that the connection is correct date day=new date (); SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");//Generate JSON string jsonobject JSON = new Jsonobject (); Json.put ("id", "1"); Json.put ("name", "Zhang San"); Json.put ("pwd", "123456"); SYSTEM.OUT.PRINTLN (JSON);D ocument testdocument = new Document () Testdocument.put ("Times", Df.format (day));// Insert Time Testdocument.put ("name", "Zhangjun"); Insert name Testdocument.put ("info", json.tostring ()); Insert JSON string list<document> documents = new arraylist<document> ();d ocuments.add (testdocument); Db.insertcollection ("Test_log_info", documents);} 

  

3. Querying data

/** * Get Collection * * @param collectionname * Set name * @param testdocument * conditions, support many pairs of conditions * @return * */publi C mongocursor<document> GetCollection (String collectionname, Document testdocument) {mongocursor<document > mongocursor = null;try {mongocollection<document> collection = Mongodatabase.getcollection (CollectionName) ; finditerable<document> resultdocument = Collection.find (testdocument); mongocursor = ResultDocument.iterator () ;} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();} return mongocursor;}  public static void Main (string[] args) {MongoDB2 db=new MongoDB2 ();d b.mongoconnect ();//Confirm connection Correct document Testdocument = new Document (); Testdocument.put ("Name", "Zhangjun"); mongocursor<document> resultdocument = db.getcollection ("Test_log_info", testdocument); while ( Resultdocument.hasnext ()) {System.out.println (Resultdocument.next ());//Get All SYSTEM.OUT.PRINTLN ( Resultdocument.next (). Get ("_id")); Get a Value}}

Java uses 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.