MongoDB Series Tutorial (vi): Java operations MongoDB Instance _mongodb

Source: Internet
Author: User
Tags mongoclient mongodb

Java operation of the MySQL database code we already know, delete and change, Java to MongoDB database is similar operation, first database connection, and then operation.

First we enter into the admin database, and then set up their own database Testmongodb, into the admin database, you can directly into the TESTMONGODB, because users can access the system's database, is Super Administrator, use Testmongodb, Set the username and password for the database, Db.adduser (' root ', ' root ') so that we can connect to the database in the program, and implement the additions and deletions, as shown in the code below.

The code looks like this:

Copy Code code as follows:

Package Com.mkyong.core;

Import java.net.UnknownHostException;
Import Java.util.Date;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.Mongo;
Import com.mongodb.MongoException;

/**
* Java + MongoDB Hello World Example
*
*/
public class App {
public static void Main (string[] args) {

try {

/**** Connect to MongoDB ****/
Since 2.10.0, uses mongoclient
Mongoclient MONGO = new Mongoclient ("localhost", 27017);

Mongo Mongo = new Mongo ("127.0.0.1", 27017);


/**** Get Database ****/
If database doesn ' t exists, MongoDB'll create it for you
DB db = Mongo.getdb ("Testmongodb");
Database username root and password root
Boolean OK = db.authenticate ("root", "root". ToCharArray ());
if (OK) {
SYSTEM.OUT.PRINTLN ("DB connection success! ");

}{
SYSTEM.OUT.PRINTLN ("DB connection fail!") ");
}
/**** get collection/table from ' Testmongodb ' ****/
If collection doesn ' t exists, MongoDB'll create it for you
Dbcollection table = db.getcollection ("user");

/**** Insert ****/
Create a document to store key and value
Basicdbobject document = new Basicdbobject ();
Document.put ("name", "Mkyong");
Document.put ("Age", 30);
Document.put ("CreatedDate", New Date ());
Table.insert (document);

/**** Find and display ****/
Basicdbobject searchquery = new Basicdbobject ();
Searchquery.put ("name", "Mkyong");

dbcursor cursor = Table.find (searchquery);

while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}

/**** Update ****/
Search document where name= "Mkyong" and update it with new values
Basicdbobject query = new Basicdbobject ();
Query.put ("name", "Mkyong");

Basicdbobject newdocument = new Basicdbobject ();
Newdocument.put ("name", "mkyong-updated");

Basicdbobject updateobj = new Basicdbobject ();
Updateobj.put ("$set", newdocument);

Table.update (query, updateobj);

/**** Find and display ****/
Basicdbobject SearchQuery2
= new Basicdbobject (). Append ("name", "mkyong-updated");

Dbcursor Cursor2 = Table.find (SearchQuery2);

while (Cursor2.hasnext ()) {
System.out.println (Cursor2.next ());
}

/**** done ****/
System.out.println ("Done");

catch (Unknownhostexception e) {
E.printstacktrace ();
catch (Mongoexception e) {
E.printstacktrace ();
}

}
}

The console input results are as follows:

Copy Code code as follows:

DB connection success!
DB connection Fail!
{"_id": {"$oid": "544073c4d58dfa6e469555ba"}, "name": "Mkyong", "Age": "CreatedDate": {"$date": "2014-10-1 7t01:41:24.479z "}}
{"_id": {"$oid": "543e154bd58d704982fd38f0"}, "name": "Mkyong-updated", "Age": "CreatedDate": {"$date": "2 014-10-15t06:33:47.321z "}}
{"_id": {"$oid": "5440719dd58d08a207605c8e"}, "name": "Mkyong-updated", "Age": "CreatedDate": {"$date": "2 014-10-17t01:32:13.922z "}}
{"_id": {"$oid": "544073c4d58dfa6e469555ba"}, "name": "Mkyong-updated", "Age": "CreatedDate": {"$date": "2 014-10-17t01:41:24.479z "}}
Done


SOURCE Download: Http://xiazai.jb51.net/201503/other/mongodb_helloworld.zip

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.