Mongdb Drivar for Java 3.0 version of the Mongo-java-driver-3.0.0.jar use

Source: Internet
Author: User
Tags bulk insert mongoclient mongodb tojson

This article uses the latest version 3.0 driver package. Maven Address

<dependency>
	<groupId>org.mongodb</groupId>
	<artifactid>mongo-java-driver</ artifactid>
	<version>3.0.0</version>
</dependency>


Note that the 2.6 version of the Java driver and the old version is very different, this article is based on the 3.0 version of the driver
No authentication connection MONGDB server

Import com.mongodb.MongoClient;
Import com.mongodb.MongoClientOptions;
Import com.mongodb.MongoCredential;
Import com.mongodb.MongoException;
Import Com.mongodb.WriteConcern;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DBObject;
Import Com.mongodb.DBCursor;
Import com.mongodb.ServerAddress;
Import com.mongodb.client.MongoCollection;

Import Com.mongodb.client.MongoDatabase;
Import java.net.InetAddress;
Import java.net.InterfaceAddress;
Import java.net.UnknownHostException;
Import java.util.ArrayList;
Import Java.util.Arrays;

Import java.util.List;

Import org.bson.Document; Do not require authentication public class Auth_no {/** * Obtain password-authenticated client * @param IP * @param port * @return/public static Mon
		Goclient getclient (String ip,int port) {mongoclient client=null;
		try {mongoclientoptions.builder build = new Mongoclientoptions.builder ();
		With data maximum connection number build.connectionsperhost (50); If all of the current connection are in use, then each CONNECtion can have 50 threads queued for Build.threadsallowedtoblockforconnectionmultiplier (50);
		Build.connecttimeout (1 * 60 * 1000);
		Build.maxwaittime (2 * 60 * 1000);
		Mongoclientoptions options = Build.build ();
	
			InetAddress inetaddress;
		
		inetaddress = Inetaddress.getbyname (IP);
		ServerAddress addr=new serveraddress (inetaddress, port);/Set Address client = new Mongoclient (addr, options);
		catch (Unknownhostexception e) {//TODO auto-generated catch block E.printstacktrace ();
	return to client; public static void Main (String args[]) throws Unknownhostexception {Mongoclientoptions.builder build = new Mongo
		Clientoptions.builder ();
		With data maximum connection number build.connectionsperhost (50);
		If all current connection are in use, 50 threads can be queued for build.threadsallowedtoblockforconnectionmultiplier (50) on each connection;
		Build.connecttimeout (1 * 60 * 1000);
		Build.maxwaittime (2 * 60 * 1000);
		Mongoclientoptions options = Build.build ();
		InetAddress inetaddress=inetaddress.getbyname ("127.0.0.1"); ServeRaddress addr=new serveraddress (inetaddress, 2222);//Set address mongoclient client = new Mongoclient (addr, options);

		Gets the database test, which does not exist, automatically establishes the database Mongodatabase db = Client.getdatabase ("Lhy");
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the datasheet in the relational database) mongocollection<document> users = db.getcollection ("Lhy");
		Document document = new document ();
		Document.append ("FirstName", "lei");
		Document.append ("Address", "Sichuan Chengdu");
		Users.insertone (document);
	Mongoclient must be close to release the Resource Client.close () after use; }
}

Need certification

Import com.mongodb.MongoClient;
Import com.mongodb.MongoClientOptions;
Import Com.mongodb.MongoClientURI;
Import com.mongodb.MongoCredential;
Import com.mongodb.MongoException;
Import Com.mongodb.WriteConcern;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DBObject;
Import Com.mongodb.DBCursor;
Import com.mongodb.ServerAddress;
Import com.mongodb.client.MongoCollection;

Import Com.mongodb.client.MongoDatabase;
Import java.net.InetAddress;
Import java.net.InterfaceAddress;
Import java.net.UnknownHostException;
Import java.util.ArrayList;
Import Java.util.Arrays;

Import java.util.List;

Import org.bson.Document; /** * Requires authentication * @author Administrator * */public class AUTH_OK {/** * First authentication method * * public static void Auth1 () 
		{String SURI = String.Format ("mongodb://%s:%s@%s:%d/%s", "lhy1", "123", "localhost", 27017, "Lhy"); 
		Mongoclienturi uri = new Mongoclienturi (SURI); Mongoclient mongoclient = new MONGOCLIent (URI);
		Mongodatabase db = Mongoclient.getdatabase ("Lhy");
		mongocollection<document> users = db.getcollection ("Lhy");
		Document document = new document ();
		Document.append ("AAA", "lei");
		Document.append ("BBB", "Sichuan Chengdu");
		Users.insertone (document);
	Mongoclient.close (); /** * The second authentication method * @throws Unknownhostexception */public static void Auth2 () throws unknownhostexception{Mon
		Goclientoptions.builder build = new Mongoclientoptions.builder ();
		With data maximum connection number build.connectionsperhost (50);
		If all current connection are in use, 50 threads can be queued for build.threadsallowedtoblockforconnectionmultiplier (50) on each connection;
		Build.connecttimeout (1 * 60 * 1000);

		Build.maxwaittime (2 * 60 * 1000);
		Mongoclientoptions options = Build.build ();
		Mongocredential crclientedentials = mongocredential. Createscramsha1credential ("Lhy1", "Lhy", "123". ToCharArray ());
		list<mongocredential> credentialslist = new arraylist<mongocredential> (); Credentialslist.Add (crclientedentials);//Voucher list, in English a database may have multiple account password inetaddress inetaddress=inetaddress.getbyname ("127.0.0.1"); ServerAddress addr=new serveraddress (inetaddress, 27017);//Set address mongoclient client = new Mongoclient (addr, CREDENTIALSL

		ist, options);

		Gets the database test, which does not exist, automatically establishes the database Mongodatabase db = Client.getdatabase ("Lhy");
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the datasheet in the relational database) mongocollection<document> users = db.getcollection ("Lhy");
		Document document = new document ();
		Document.append ("FirstName", "lei");
		Document.append ("Address", "Sichuan Chengdu");
		Users.insertone (document);
	Mongoclient must be close to release the Resource Client.close () after use;
	public static void Main (String args[]) throws Unknownhostexception {auth1 (); }
}

Increase
Import java.util.ArrayList;

Import java.util.List;

Import org.bson.Document;
Import com.mongodb.MongoClient;
Import com.mongodb.client.MongoCollection;
Import Com.mongodb.client.MongoCursor;


Import Com.mongodb.client.MongoDatabase; public class M_insert {/** * Single insert/public static void Insert_1 () {mongoclient client=auth_no.getclient ("12
		7.0.0.1 ", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");
		Mongocollection<document> collection = Db.getcollection ("Lhy");
		Document document = new document ();
		Document.append ("name", "ddd aaa");
		Document.append ("Age", "Lhy gggg");
		
		

		Collection.insertone (document);
	Mongoclient must be close to release the Resource Client.close () after use;
		/** * BULK INSERT */public static void Insert_2 () {mongoclient client=auth_no.getclient ("127.0.0.1", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy"); Mongocollection<document> Collection = Db.getcollection ("Lhy");
		 Create a list that contains multiple documents list<document> documents = new arraylist<document> ();
		 for (int i = 0; i < i++) {Documents.Add (new Document ("I", I));

	///Insert a list into the document Collection.insertmany (documents);
	public static void Main (string[] args) {insert_1 ();
 }

}

Remove

Import static Com.mongodb.client.model.Filters.eq;

Import static Com.mongodb.client.model.Filters.gte;

Import org.bson.Document;
Import com.mongodb.MongoClient;
Import com.mongodb.client.MongoCollection;
Import Com.mongodb.client.MongoDatabase;


Import Com.mongodb.client.result.DeleteResult;
		public class M_delete {public static void Delete_1 () {mongoclient client=auth_no.getclient ("127.0.0.1", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");
		Mongocollection<document> collection = Db.getcollection ("Lhy");
		Deletes the first qualifying data collection.deleteone (eq ("name", "Lhy"));
		 To get all the documents, you can see that there are no 110 for this number for (document Cur:collection.find ()) {System.out.println (Cur.tojson ());
		//Delete all eligible data and return the result deleteresult Deleteresult = Collection.deletemany (GTE ("I", 100));
		The number of rows deleted by the output System.out.println (Deleteresult.getdeletedcount ()); Get all documents, all I&GT;=100 data is not available for (document Cur:collection.find ()) {System. Out.println (Cur.tojson ());
		} public static void Main (string[] args) {mongoclient client=auth_no.getclient ("127.0.0.1", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");
		Mongocollection<document> collection = Db.getcollection ("Lhy");
	Collection.drop ();
 }
}

Modify

Import static Com.mongodb.client.model.Filters.eq;
Import static Com.mongodb.client.model.Filters.gte;

Import static com.mongodb.client.model.Filters.lt;

Import org.bson.Document;
Import com.mongodb.MongoClient;
Import com.mongodb.client.MongoCollection;
Import Com.mongodb.client.MongoDatabase;
Import Com.mongodb.client.result.DeleteResult;


Import Com.mongodb.client.result.UpdateResult; public class M_update {* * Modified parameters: $inc Add $mul to the specified element $rename modify the element name $setOnInsert if this element is not previously added, no changes are made Set modifies the value of a SET element $unset removes a specific element $min if the original data is larger then it is not modified, otherwise it is modified to the specified value $max to the current time as opposed to the $min $currentDate./public static void U
		Pdate_1 () {mongoclient client=auth_no.getclient ("127.0.0.1", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");
		Mongocollection<document> collection = Db.getcollection ("Lhy");
		Modify the first qualifying data//$set to modify Collection.updateone (eq ("I", "New Document" ("$set", New document ("I", 110)); BeenWith all of the documents, you can see that the previous 10 has become a for (document Cur:collection.find ()) {System.out.println (Cur.tojson ()); //Bulk Modify the data and return the modified result, saying that all results less than 100 are updateresult Updateresult = Collection.updatemany (LT ("I"), new Documen
		T ("$inc", New Document ("I", 100));
		Displays the number of rows that have changed System.out.println (Updateresult.getmodifiedcount ());
		 Get all the documents you can see except for the 110 others that have just been modified (document Cur:collection.find ()) {System.out.println (Cur.tojson ());
 } public static void Main (string[] args) {}}

Query

Import static Com.mongodb.client.model.Filters.and;
Import static Com.mongodb.client.model.Filters.eq;
Import static com.mongodb.client.model.Filters.exists;
Import static com.mongodb.client.model.Filters.gt;

Import static Com.mongodb.client.model.Filters.lte;

Import org.bson.Document;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.Block;
Import com.mongodb.MongoClient;
Import com.mongodb.client.MongoCollection;
Import Com.mongodb.client.MongoCursor;


Import Com.mongodb.client.MongoDatabase;
		public class M_query {public static void Query_1 () {mongoclient client=auth_no.getclient ("127.0.0.1", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");
		 Mongocollection<document> collection = Db.getcollection ("Lhy");
		
		Displays the number of documents in the collection System.out.println (Collection.count ());
		 The first document in the query collection MyDoc = Collection.find ().
		
		 System.out.println (Mydoc.tojson ()); Traverse documentation 1 for (document Cur:collectIon.find ()) {System.out.println (Cur.tojson ());
		 //Traverse Document 2 mongocursor<document> cursor = Collection.find (). iterator ();
		 try {while (Cursor.hasnext ()) {System.out.println () Cursor.next (). Tojson ());
		 finally {cursor.close ();
		}/** * Condition query/public static void Query_2 () {mongoclient client=auth_no.getclient ("127.0.0.1", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");

			Mongocollection<document> collection = Db.getcollection ("Lhy");
			 To obtain a eq:== document MYDOC = Collection.find (eq ("I",)).

			System.out.println (Mydoc.tojson ()); Get multiple data at once through a query statement block<document> printblock = new block<document> () {@Override public void appl
			 Y (Final Document document) {SYSTEM.OUT.PRINTLN (Document.tojson ());
			}
			 };
			Gets all Collection.find (GT ("I"), greater than 50). ForEach (Printblock); Greater than 50 is less than collection.find (GT ("I", M), LTE ("I")). ForEach (Printblock); The output document is sorted,-1 is decremented, 1 is incremented//The official document is an example of error: http:mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/ quick-tour/#sorting-documents Document myDoc1 = Collection.find (exists ("I")). Sort (New Basicdbobject ("I",-1)). Fir
			 St ();

			System.out.println (Mydoc1.tojson ()); The element in the selective output result, 0 is not displayed, 1 is the display//The example in the official document is not available: http:mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/
			 quick-tour/#projecting-fields basicdbobject exclude = new Basicdbobject ();
			  Exclude.append ("_id", 0);
			 Exclude.append ("Count", 0);
			 Exclude.append ("name", 1);
			 Exclude.append ("info", 1);
			 Document myDoc2 = Collection.find (). projection (exclude).
		
	System.out.println (Mydoc2.tojson ());
 public static void Main (string[] args) {}}

multi-statement execution

Import static Com.mongodb.client.model.Filters.eq;

Import static Com.mongodb.client.model.Filters.gte;
Import java.util.ArrayList;
Import Java.util.Arrays;

Import java.util.List;

Import org.bson.Document;
Import com.mongodb.MongoClient;
Import com.mongodb.client.MongoCollection;
Import Com.mongodb.client.MongoDatabase;
Import com.mongodb.client.model.BulkWriteOptions;
Import Com.mongodb.client.model.DeleteOneModel;
Import Com.mongodb.client.model.InsertOneModel;
Import Com.mongodb.client.model.ReplaceOneModel;
Import Com.mongodb.client.model.UpdateOneModel;
Import Com.mongodb.client.model.WriteModel;


Import Com.mongodb.client.result.DeleteResult; public class M_builk {/** * in order execute/public static void Builk_1 () {mongoclient client=auth_no.getclient ("127.0.0
		.1 ", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");
	
		Mongocollection<document> collection = Db.getcollection ("Lhy"); Execute List list=new Arraylis in sequence of statementsT ();
		List.add (New Insertonemodel ("name", 4));
		List.add (New Insertonemodel ("name", 5));
		List.add (New Updateonemodel ("name", 4), New document ("$set", New Document ("X", 2)));
	
		 List.add (New Deleteonemodel ("name", 5));
		 Collection.bulkwrite (list);
		 Get all documents for (document Cur:collection.find ()) {System.out.println (Cur.tojson ());
		}/** * does not execute in order */public static void Builk_2 () {mongoclient client=auth_no.getclient ("127.0.0.1", 2222);
		Gets the data collection, which does not exist, automatically establishes the collection (equivalent to the data table in the relational database) Mongodatabase db = Client.getdatabase ("Lhy");

		Mongocollection<document> collection = Db.getcollection ("Lhy");
		/** * Do not follow the order of the above * * * List list=new ArrayList ();
		List.add (New Insertonemodel ("name", 4));
		List.add (New Insertonemodel ("name", 5));
		List.add (New Updateonemodel ("name", 4), New document ("$set", New Document ("X", 2))); List.add (New Deleteonemodel, new document ("name", 5));
		Collection.bulkwrite (list, new Bulkwriteoptions (). Ordered (false));
		 Get all documents for (document Cur:collection.find ()) {System.out.println (Cur.tojson ());
	} public static void Main (string[] args) {builk_1 ();
 }
}



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.