original linkhttp://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
Introduction
The purpose of this article is to give you a simple idea of how to use MongoDB's Java-driver driver, and when you have read this article you can refer to other articles for more information.
Download Java-driver Driver
You can download the required drivers here .
Add the Java-driver driver to copy the downloaded Mongo-java-driver-2.12.3.jar to your Lib directory.
Get database objects
Mongoclient mongoclient = new Mongoclient ("localhost", 5000); 5000 is the instance port number, and the default boot port number is 27017
DB db = Mongoclient.getdb ("MyDB"); You must first create a database
Gets the collection name set<string> colls = Db.getcollectionnames ();
for (String s:colls) {
System.out.println (s);
}
Gets the collection object Dbcollection coll = db.getcollection ("blog");
Gets the number of collection documents
System.out.println (Coll.getcount ());
Insert a document Basicdbobject doc = new Basicdbobject ("name", "MongoDB")
. Append ("type", "Database")
. Append ("Count", 1)
. Append ("Info", New Basicdbobject ("X", 203). Append ("Y", 102));
Coll.insert (DOC);
Inserting multiple documents
for (int i=0; i <; i++) {
Coll.insert (New Basicdbobject ("I", I));
}
Querying a document that satisfies a condition by using a cursor
Basicdbobject query = new Basicdbobject ("I", 71);
dbcursor cursor = coll.find (query);
try {
while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}
} finally {
Cursor.close ();
}
Bulkwriteoperation builder = coll.initializeorderedbulkoperation ();
Builder.insert (New Basicdbobject ("_id", 1));
Builder.insert (New Basicdbobject ("_id", 2));
Builder.insert (New Basicdbobject ("_id", 3));
Update the existing document Builder.find (new Basicdbobject ("_id", 1)). Updateone (New Basicdbobject ("$set", New Basicdbobject ("X", 2 )));
Delete the existing document Builder.find (new Basicdbobject ("_id", 2)). Removeone ();
Builder.find (New Basicdbobject ("_id", 3)). Replaceone (New Basicdbobject ("_id", 3). Append ("X", 4));
Bulkwriteresult result = Builder.execute ();