The following is a brief overview of accessing the database using MongoDB's Java driver.
Using MongoDB's Java driver is simple, just make sure to add the Mongo.jar file to the classpath.
1). Get the connection:
In order to connect to MongoDB, you need to know the name of the database to connect to. If the library does not exist, MongoDB will create a new library. In addition, you need to specify the server address and port when connecting. Here are three ways to connect a local machine's mydb database:
Mongoclient mongoclient = new Mongoclient (); Mongoclient mongoclient = new Mongoclient ("localhost"); Mongoclient mongoclient = new Mongoclient ("localhost", 27017); Mongoclient mongoclient = new Mongoclient (arrays.aslist (New serveraddress ("localhost", 27017), New ServerAddress (" localhost ", 27018), New serveraddress (" localhost ", 27019)));D b DB = Mongoclient.getdb (" MyDB ");
At this point, the DB object is connected to the database specified by the MONGODB server and can then be manipulated.
The Mongoclient class is thread-safe and thread-shared. Typically, only one mongoclient instance is created in the application for the specified DB cluster. If you need to create multiple mongoclient samples for some reason, you need to be aware of the following:
All resources are limited (maximum number of connections, etc.) applied to each mongoclient instance;
when destroying an instance, make sure to use Mongoclient.close () to free up resources. 2). Identity authentication:
MongoDB can run in Safe mode, which uses a username and password to authenticate to access the database. In safe mode, any client application must provide a user name and password before any action is made. In the Java driver, mongoclient can be used in the following ways:
Mongoclient mongoclient = new Mongoclient ();D b DB = mongoclient.getdb ("Test"); Boolean auth = Db.authenticate (MyUserName, MyPassword);
Returns true if the user name and password are verified in the database, otherwise false. Detailed information can be obtained by viewing the MongoDB log. Mostly MongoDB does not require identity authentication in a trusted environment.
3). Get all Collections:
There are 0 to multiple collections per database. They can be retrieved from the DB object:
Set<string> colls = Db.getcollectionnames (); for (String s:colls) {System.out.println (s);}
4). Gets a collection:
to get a collection, simply call the GetCollection (sring CollectionName) method to specify the collection name: Dbcollection coll = db.getcollection ("testcollection");
Once the collection object is acquired, it can be queried, inserted into the data, and so on.
5). Set the Write Concern:
for 2.10.0 and later versions, the default write concern is writeconcern.acknowledged, but you can change the default settings: Mongoclient.setwriteconcern (writeconcern.journaled);
There are many options available for Wirte concern. In addition, write concern can only be changed at the database, collection, or even single operation level by default. For more information, refer to the API documentation http://api.mongodb.org/java/current/index.html
。
6). Insert a document:
once you get the collection object, you can insert the document in the collection. For example, a document represented by a JSON format: {"Name": "MongoDB", "type": "Database", "Count": 1, "info": {x:203,y:102}}
Please note that there is an inline document in the document above. Use the Basicdbobject class to create a document (including internal documents), and then call the Insert () method of the collection to insert the 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);
7). The FindOne () method finds the first document in the collection:
Use the FindOne () method to isolate the document that was inserted in the previous step, which returns a single document (different from the return value of the Find () operation in Dbcursor). This is useful for situations where only one document or only the first document is concerned. There is no need to handle cursors here.
DBObject MyDoc = Coll.findone (); System.out.println (MYDOC);
Output:
{"_id": "49902cde5162504500b45c2c", "name": "MongoDB", "type": "Database", "Count": 1, "info": {"x": 203, "Y": 1 02}}
8). Add more than one document:
To facilitate querying, insert multiple simple documents into the collection, which are in the form of;
{"I": value}
To insert a document using a loop:
for (int i=0; i <; i++) {Coll.insert (new Basicdbobject ("I", I));}
Note that we can insert a different "shape" document into the same collection, which is the mode free (schema-free) feature of MongoDB.
9). Statistics collection Chinese documents:
Now that you have inserted 101 documents (the first and 100 loops), use the GetCount () method to query:
System.out.println (Coll.getcount ());
the number 101 will be printed out.
10). Use cursors to query all documents:
In order to get all the documents in the collection, the Find () method is used. The Find () method returns a Dbcursor object that iterates through the collection of documents that are queried. All documents are queried and output as follows:
dbcursor cursor = Coll.find (); try {while (Cursor.hasnext ()) {System.out.println (Cursor.next ())}} finally {Cursor.clos E ();}
The 101 documents in the collection will be printed.
11). Querying a single document
You can query a partial document of a collection by passing a parameter to the Find () method. For example, a document that has a value of 71 as the "I" field of the document is isolated:
Basicdbobject query = new Basicdbobject ("I", +); cursor = coll.find (query); try {while (Cursor.hasnext ()) {System.out.pri Ntln (Cursor.next ()); }} finally {Cursor.close ();}
A document will be printed:
{"_id": "49903677516250c1008d624e", "I": 71}
You may have seen the $ operator in the MONGODB documentation and sample code, for example:
Db.things.find ({j: {$ne: 3}, K: {$gt: 10}});
In the Java driver, these are all represented as string keys, using the inline dbobject:
query = new Basicdbobject ("J", New Basicdbobject ("$ne", 3)). Append ("K", New Basicdbobject ("$gt", ten)); cursor = Coll.find ( query); try {while (Cursor.hasnext ()) {System.out.println (Cursor.next ())}} finally {Cursor.close ()}
12). Query Multiple documents:
You can use a query condition to get a collection of documents. For example, get all the documents for the "I" >50:
query = new Basicdbobject ("I", New Basicdbobject ("$GT"), cursor = coll.find (query), try {while (Cursor.hasnext ()) {Sys Tem.out.println (Cursor.next ());}} finally {cursor.close ();}
To query a range, such as 20<i<=30:
query = new Basicdbobject ("I", New Basicdbobject ("$gt"). Append ("$lte"); cursor = testcollection.find (query); try {while (Cursor.hasnext ()) {System.out.println (Cursor.next ());}} finally {cursor.close ();}
13). MaxTime
MongoDB2.6 introduces the query timeout feature:
Coll.find (). MaxTime (1, SECONDS). Count ();
The above example sets MaxTime to one second and the query will abort after one second.
14). Bulk Operation:
MongoDB2.6 provides two new commands for bulk operations, including bulk INSERT, modify, and delete operations:
①. ordered batch operations:
All operations are performed sequentially, and the first write error is an output error.
②. Unordered Bulk Operations:
Performs all operations in parallel, assembling all errors. Unordered bulk operations do not guarantee the order of execution.
Here are simple examples of ordered bulk operations and unordered bulk operations:
1. Ordered bulk operation bulkwriteoperation builder = coll.initializeorderedbulkoperation (); Builder.insert (New Basicdbobject ("_id", 1) ), Builder.insert (New Basicdbobject ("_id", 2)), Builder.insert (New Basicdbobject ("_id", 3)); Builder.find (new Basicdbobject ("_id", 1)). Updateone (New Basicdbobject ("$set", New Basicdbobject ("X", 2)); 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 ();//2. Unordered Bulk Operations builder = coll.initializeunorderedbulkoperation (); Builder.find (New Basicdbobject ("_id", 1)). Removeone (); Builder.find (New Basicdbobject ("_id", 2)). Removeone (); result = Builder.execute (); ). parallelscan:mongodb2.6 adds the Parallelcollectionscan command, allowing multiple cursors to be used to read the entire collection: parallelscanoptions parallelscanoptions = Parallelscanoptions.builder (). Numcursors (3). BatchSize () build (); list<cursor> cursors = Coll.parallelscan (parallelscanoptions); for (Cursor pcursor:cursors) {while (pcursor. Hasnext ()) {System.out.println ((Pcursor.next ()));}
- management features guided tour
1) . Get the list of databases:
You can call the Getbatabasenames () method to get to the list of databases:
Mongoclient mongoclient = new Mongoclient (); for (String s:mongoclient.getdatabasenames ()) {System.out.println (s);}
Calling Mongoclient.getdb () does not create a database. It is created whenever a database has a write operation, such as creating an index, or creating a collection or inserting a document.
2). Delete a database:
Mongoclient Instances can delete a database by name: Mongoclient mongoclient = new Mongoclient (); Mongoclient.dropdatabase ("databasetobedropped");
3). Create a collection :
There are two ways to create a collection, insert a document when the collection does not exist, or call the CreateCollection command:
db = Mongoclient.getdb ("MyDB");d b.createcollection ("Testcollection", New Basicdbobject ("capped", true). Append ("Size ", 1048576));
4). Get the Collection list:
You can get a list of collections by calling the Getcollectionnames () method of the DB object:
For (String s:db.getcollectionnames ()) {System.out.println (s);}
Output:
System.indexestestcollection
5). Delete a collection:
You can delete a collection by calling the Deop () method of the collection object:
Dbcollection testcollection = db.getcollection ("testcollection"); Testcollection.drop (); System.out.println (Db.getcollectionnames ());
6). Gets the list of indexes for a collection:
You can get an indexed list by calling the GetIndexInfo () method of the collection object:
list<dbobject> list = Coll.getindexinfo (); for (DBObject o:list) {System.out.println (O.get ("key"));}
You will see output similar to the following:
{"V": 1, "key": {"_id": 1}, "name": "_id_", "ns": "Mydb.testcollection"} {"V": 1, "key": {"I": 1}, "name" : "I_1", "ns": "Mydb.testcollection"} {"V": 1, "key": {"loc": "2dsphere"}, "name": "Loc_2dsphere", ...} {"V": 1, "key": {"_fts": "Text", "_FTSX": 1}, "name": "Content_text", ...}
7). Create an index:
MongoDB supports indexes, and they are easily added to a collection. To create an index, you only need to specify the fields that you want to index, and specify all ascending (1) or Descending (-1). The following is an ascending index created on the I field:
Coll.createindex (New Basicdbobject ("I", 1));
8). Geo Index:
MongoDB supports various geo-spatial indexes. In the following example, a "2dsphere" index is created, which can be queried using a standard Geojson tag. Creating a "2dsphere" index requires the string "2dsphere" to be specified in the document: Coll.createindex (New Basicdbobject ("Loc", "2dsphere"));
There are several ways to query a "2dsphere" index within 500 meters of the place:
Basicdblist coordinates = new Basicdblist () coordinates.put (0, -73.97); Coordinates.put (1, 40.77); Coll.insert (new Basicdbobject ("name", "Central Park"). Append ("loc", New Basicdbobject ("type", "point"). Append ("coordinates", coordinates)). Append ("category", "Parks"); Coordinates.put (0, -73.88); Coordinates.put (1, 40.78); Coll.insert (new Basicdbobject ("name", "La Guardia Airport"). Append ("loc", New Basicdbobject ("type", "point"). Append ("coordinates", coordinates)). Append ("category", "Airport")); Basicdblist mylocation = new Basicdblist () mylocation.put (0, -73.965); Mylocation.put (1, 40.769); myDoc = Coll.findone ( New Basicdbobject ("Loc", New Basicdbobject ("$near", New Basicdbobject ("$geometry", New Basicdbobject ("type", "point"). Append ("coordinates", mylocation)). Append ("$maxDistance", 500))); System.out.println (Mydoc.get ("name"));
9) . Text index:
MongoDB provides a text index to support text searches of string content. A text index can contain the value of any field, which is a string or an array of strings. Creating a text index requires specifying "text" in the document: Coll.createindex (New Basicdbobject ("Content", "text"));
MongoDB2.6 Chinese This index is integrated into the main query language and is enabled by default:
Insert Document Coll.insert (new Basicdbobject ("_id", 0). Append ("Content", "textual Content"), Coll.insert (New Basicdbobject (" _id ", 1). Append (" Content "," additional content ")) Coll.insert (New Basicdbobject (" _id ", 2). Append (" Content "," Irrelevant content ")); Basicdbobject search = new Basicdbobject ("$search", "Textual Content-irrelevant"); Basicdbobject textsearch = new Basicdbobject ("$text", search); int matchcount = Coll.find (textsearch). Count (); System.out.println ("Text Search matches:" + matchcount); textsearch = new Basicdbobject ("$text", Search.append ("$ Language "," 中文版 "); MatchCount = Coll.find (textsearch). Count (); System.out.println ("Text Search Matches (中文版):" + MatchCount); Basicdbobject projection = new Basicdbobject ("Score", New Basicdbobject ("$meta", "Textscore")); MyDoc = Coll.findone ( Textsearch, projection); System.out.println ("Highest scoring Document:" + MyDoc);
The following will be printed:
Text Search Matches:2text Search matches (中文版): 2Highest scoring Document: {"_id": 1, "Content": "Additional cont Ent "," Score ": 0.75}
For more information on text indexing, please refer to http://docs.mongodb.org/manual/core/index-text/ and the http://docs.mongodb.org/manual/reference/operator/query/text/
Tags: java database mongodbnosql