2015年10月25日 星期日

[ MongoDB 文件 ] Getting Started - MongoDB Driver Quick Tour

Source From Here 
Make a Connection 
Following example shows ways to connect to the database mydb on the local machine. If the database does not exist, MongoDB will create it for you. 
  1. // To directly connect to a single MongoDB server  
  2. // (this will not auto-discover the primary even if it's a member of a replica set)  
  3. MongoClient mongoClient = new MongoClient();  
  4.   
  5. // or  
  6. MongoClient mongoClient = new MongoClient( "localhost" );  
  7.   
  8. // or  
  9. MongoClient mongoClient = new MongoClient( "localhost" , 27017 );  
  10.   
  11. // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members  
  12. MongoClient mongoClient = new MongoClient(  
  13.   Arrays.asList(new ServerAddress("localhost"27017),  
  14.                 new ServerAddress("localhost"27018),  
  15.                 new ServerAddress("localhost"27019)));  
  16.   
  17. // or use a connection string  
  18. MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");  
  19. MongoClient mongoClient = new MongoClient(connectionString);  
  20.   
  21. MongoDatabase database = mongoClient.getDatabase("mydb");  
At this point, the database object will be a connection to a MongoDB server for the specified database. 

MongoClient 
The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads. Typically you only create one MongoClient instance for a given database cluster and use it across your application. When creating multiple instances: 
* All resource usage limits (max connections, etc) apply per MongoClient instance
* To dispose of an instance, make sure you call MongoClient.close() to clean up resources

Get a Collection 
To get a collection to operate upon, specify the name of the collection to the getCollection() method from object which implement MongoDatabase interface. The following example gets the collection test
  1. MongoCollection collection = database.getCollection("test");  
Insert a Document 
Once you have the collection object (MongoCollection), you can insert documents into the collection. For example, consider the following JSON document; the document contains a field info which is an embedded document: 
  1. {  
  2.    "name" : "MongoDB",  
  3.    "type" : "database",  
  4.    "count" : 1,  
  5.    "info" : {  
  6.                x : 203,  
  7.                y : 102  
  8.              }  
  9. }  
To create the document using the Java driver, use the Document class. You can use this class to create the embedded document as well. 
  1. Document doc = new Document("name""MongoDB")  
  2.                .append("type""database")  
  3.                .append("count"1)  
  4.                .append("info"new Document("x"203).append("y"102));  
To insert the document into the collection, use the insertOne() method. 
  1. collection.insertOne(doc);  
Add Multiple Documents 
To add multiple documents, you can use the insertMany() method. The following example will add multiple documents of the form: 
  1. "i" : value }  
Create the documents in a loop. 
  1. List documents = new ArrayList();  
  2. for (int i = 0; i < 100; i++) {  
  3.     documents.add(new Document("i", i));  
  4. }  
To insert these documents to the collection, pass the list of documents to the insertMany() method. 
  1. collection.insertMany(documents);  
Count Documents in A Collection 
Now that we’ve inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the count() method. The following code should print 101. 
  1. System.out.println(collection.count());  
Query the Collection 
Use the find() method to query the collection. 

Find the First Document in a Collection 
To get the first document in the collection, call the first() method on the find() operation. collection.find().first() returns the first document or null rather than a cursor. This is useful for queries that should only match a single document, or if you are interested in the first document only. 

The following example prints the first document found in the collection. 
  1. Document myDoc = collection.find().first();  
  2. System.out.println(myDoc.toJson());  
The example should print the following document: 
  1. "_id" : { "$oid" : "551582c558c7b4fbacf16735" },  
  2.   "name" : "MongoDB""type" : "database""count" : 1,  
  3.   "info" : { "x" : 203"y" : 102 } }  
Note. 
The _id element has been added automatically by MongoDB to your document and your value will differ from that shown. MongoDB reserves field names that start with “_” and “$” for internal use.

Find All Documents in a Collection 
To retrieve all the documents in the collection, we will use the find() method. The find() method returns a FindIterable instance that provides a fluent interface for chaining or controlling find operations. Use the iterator() method to get an iterator over the set of documents that matched the query and iterate. The following code retrieves all documents in the collection and prints them out (101 documents): 
  1. MongoCursor cursor = collection.find().iterator();  
  2. try {  
  3.     while (cursor.hasNext()) {  
  4.         System.out.println(cursor.next().toJson());  
  5.     }  
  6. finally {  
  7.     cursor.close();  
  8. }  
Although the following idiom is permissible, its use is discouraged as the application can leak a cursor if the loop terminates early: 
  1. for (Document cur : collection.find()) {  
  2.     System.out.println(cur.toJson());  
  3. }  
Get A Single Document with a Query Filter 
We can create a filter to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the “i” field is 71, we would do the following: 
  1. import static com.mongodb.client.model.Filters.*;  
  2.   
  3. myDoc = collection.find(eq("i"71)).first();  
  4. System.out.println(myDoc.toJson());  
and it should just print just one document 
  1. "_id" : { "$oid" : "5515836e58c7b4fbc756320b" }, "i" : 71 }  
Note. 
Use the FiltersSorts and Projections helpers for simple and concise ways of building up queries.

Get a Set of Documents with a Query 
We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write: 
  1. // now use a range query to get a larger subset  
  2. Block printBlock = new Block() {  
  3.      @Override  
  4.      public void apply(final Document document) {  
  5.          System.out.println(document.toJson());  
  6.      }  
  7. };  
  8. collection.find(gt("i"50)).forEach(printBlock);  
Notice we use the forEach method on FindIterable which applies a block to each document and we print all documents where i > 50. We could also get a range, say 50 < i <= 100: 
  1. collection.find(and(gt("i"50), lte("i"100))).forEach(printBlock);  
Sorting documents 
We can also use the Sorts helpers to sort documents. We add a sort to a find query by calling the sort() method on a FindIterable. Below we use theBelow we use the }}"="" target="_new" rel="nofollow" style="color: rgb(1, 51, 107); text-decoration: none; font-family: verdana, arial, helvetica, sans-serif; font-size: 12px; line-height: 18px; background-color: rgb(250, 250, 250);">exists()helper and sort descending("i") helper to sort our documents: 


  1. myDoc = collection.find(exists("i")).sort(descending("i")).first();  
  2. System.out.println(myDoc.toJson());  
Projecting fields 
Sometimes we don’t need all the data contained in a document, the Projections helpers help build the projection parameter for the find operation. Below we’ll sort the collection, exclude the _id field and output the first matching document: 
  1. myDoc = collection.find().projection(excludeId()).first();  
  2. System.out.println(myDoc.toJson());  
Updating documents 
There are numerous update operators supported by MongoDB. 

To update at most a single document (may be 0 if none match the filter), use the updateOne method to specify the filter and the update document. Here we update the first document that meets the filter i equals 10 and set the value of i to 110: 
  1. collection.updateOne(eq("i"10), new Document("$set"new Document("i"110)));  
To update all documents matching the filter use the updateMany method. Here we increment the value of i by 100 where i is less than 100. 
  1. UpdateResult updateResult = collection.updateMany(lt("i"100),  
  2.           new Document("$inc"new Document("i"100)));  
  3. System.out.println(updateResult.getModifiedCount());  
The update methods return an UpdateResult which provides information about the operation including the number of documents modified by the update. 

Deleting documents 
To delete at most a single document (may be 0 if none match the filter) use the deleteOne method: 
  1. collection.deleteOne(eq("i"110));  
To delete all documents matching the filter use the deleteMany method. Here we delete all documents where i is greater or equal to 100: 
  1. DeleteResult deleteResult = collection.deleteMany(gte("i"100));  
  2. System.out.println(deleteResult.getDeletedCount());  
The delete methods return a DeleteResult which provides information about the operation including the number of documents deleted. 

Bulk operations 
These new commands allow for the execution of bulk insert/update/delete operations. There are two types of bulk operations: 
1. Ordered bulk operations: Executes all the operation in order and error out on the first write error.
2. Unordered bulk operations: Executes all the operations and reports any the errors. Unordered bulk operations do not guarantee order of execution.

Let’s look at two simple examples using ordered and unordered operations: 
  1. // 1. Ordered bulk operation - order is guarenteed  
  2. collection.bulkWrite(  
  3.   Arrays.asList(new InsertOneModel<>(new Document("_id"4)),  
  4.                 new InsertOneModel<>(new Document("_id"5)),  
  5.                 new InsertOneModel<>(new Document("_id"6)),  
  6.                 new UpdateOneModel<>(new Document("_id"1),  
  7.                                      new Document("$set"new Document("x"2))),  
  8.                 new DeleteOneModel<>(new Document("_id"2)),  
  9.                 new ReplaceOneModel<>(new Document("_id"3),  
  10.                                       new Document("_id"3).append("x"4))));  
  11.   
  12.   
  13. // 2. Unordered bulk operation - no guarantee of order of operation  
  14. collection.bulkWrite(  
  15.   Arrays.asList(new InsertOneModel<>(new Document("_id"4)),  
  16.                 new InsertOneModel<>(new Document("_id"5)),  
  17.                 new InsertOneModel<>(new Document("_id"6)),  
  18.                 new UpdateOneModel<>(new Document("_id"1),  
  19.                                      new Document("$set"new Document("x"2))),  
  20.                 new DeleteOneModel<>(new Document("_id"2)),  
  21.                 new ReplaceOneModel<>(new Document("_id"3),  
  22.                                       new Document("_id"3).append("x"4))),  
  23.   new BulkWriteOptions().ordered(false));  
Supplement 
Getting Started - Java Driver 
Getting Started - Insert Data 
Getting Started - Find Or Query Data 
Getting Started - Update Data 
Getting Started - Remove Data 
Getting Started - Data Aggregation

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...