MongoDB tutorial series (6) : java operates on mongodb instances

  • 2020-05-27 07:27:30
  • OfStack

We already know the code of java for mysql database, so we can add, delete, and check it. java also has a similar operation for mongodb database, which is first connected to the database, then operated.

We enter into the admin database first, and then build your own database testMongoDb, after entering admin database, can directly enter the testMongoDb, because users can enter the system database, is the super administrator, use testMongoDb, set the user name and password for the database, db. addUser (' root ', 'root'), so we connect the database in the program, and implement the add and delete, the code is shown below.

The code is 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 will 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 will 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:


    db connection success !
    db connection fail !
{ "_id" : { "$oid" : "544073c4d58dfa6e469555ba"} , "name" : "mkyong" , "age" : 30 , "createdDate" : { "$date" : "2014-10-17T01:41:24.479Z"}}
{ "_id" : { "$oid" : "543e154bd58d704982fd38f0"} , "name" : "mkyong-updated" , "age" : 30 , "createdDate" : { "$date" : "2014-10-15T06:33:47.321Z"}}
{ "_id" : { "$oid" : "5440719dd58d08a207605c8e"} , "name" : "mkyong-updated" , "age" : 30 , "createdDate" : { "$date" : "2014-10-17T01:32:13.922Z"}}
{ "_id" : { "$oid" : "544073c4d58dfa6e469555ba"} , "name" : "mkyong-updated" , "age" : 30 , "createdDate" : { "$date" : "2014-10-17T01:41:24.479Z"}}
Done


Source download: http: / / xiazai ofstack. com / 201503 / other/mongodb_helloworld zip


Related articles: