First introduce the Mongo-java-dirver driver
<!--Mongo-java-dirver--><dependency><groupid>org.mongodb</groupid><artifactid> Mongo-java-driver</artifactid><version>3.4.2</version></dependency>
Code Operation Demo:
package com.simple.database.test;import java.util.arraylist;import java.util.list;import org.bson.document;import org.bson.conversions.bson;import com.mongodb.mongoclient;import com.mongodb.client.finditerable;import com.mongodb.client.mongocollection;import com.mongodb.client.mongocursor;import com.mongodb.client.mongodatabase;import Com.mongodb.client.model.filters;/** * java Operation mongodb * @author root */public class hellomongodb {public static void main (String[] args) {try {//1, connect to MongoDB service mongoclient mc = new mongoclient ("127.0.0.1", 27017);//2, Connect to the specified database Mongodatabase db = mc.getdatabase ("Demodb"),//3, create collection//db.createcollection ("Simplelife") ;//4, Get Collection mongocollection<document> collection = db.getcollection ("Users"),//5, insert document DATA// Insertcollectiondata (collection);//6, querying document Data Findcollectiondata (collection);//7. Update the document Data//modify the document in document LIKES=100 to Likes=200 updatecollectiondata (collection);//8, Delete the first document data Collection.deletemany (Filters.eq ("likes"), Collection.deleteone (Filters.eq ("likes", 100));} catch (exception e) {e.printstacktrace (); System.out.println (E.getclass (). GetName () + "..." + e.getmessage ());} Private static void updatecollectiondata (mongocollection<document> collection) {Bson filter = filters.eq ("likes", 100);D ocument update = new document ("$set", new document ("likes", 200)); Collection.updatemany (filter, update);} Private static void findcollectiondata (mongocollection<document> collection) { Finditerable<document> finditerable = collection.find (); Mongocursor<document> mongocursor = finditerable.iterator (); while (MongoCursor.hasNext ()) { System.out.println (Mongocursor.next ());}}/** * Insert Document &NBSP;1, create document org.bson.Document parameter to key-value format * 2, create document collection list<document> * 3, inserting a collection of documents into a database collection: Mongocollection.insertmany (list<document>) * inserting a single document can be used : Mongocollection.insertone (Document) */private static void insertcollectiondata ( mongocollection<document> collection) {document document = new document (" Title ", " MongoDB ");d ocument.append (" description ", " Database "). Append (" likes ", 100). Append (" by ", "Fly"); List<document> documents = new arraylist<> ();d ocuments.add (Document); Collection.insertmany (documents); SYSTEM.OUT.PRINTLN ("The document was inserted successfully! ");}}
This article is from the "Simplelife" blog, make sure to keep this source http://simplelife.blog.51cto.com/9954761/1929886
Java Operation MongoDB