2015年12月7日 星期一

[ MongoDB 文件 ] Getting Started - Find or Query Data with Java Driver

Source From Here 
Overview 
You can use the find method to issue a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection. Queries can return all documents in a collection or only the documents that match a specified filter or criteria. You can specify the filter or criteria in a org.bson.Document and pass as a parameter to the find method. 

The find method returns query results in a FindIterable, which is an iterable object that yields documents. 

Prerequisites 
The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset. Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable db to access the test database. Include the following import statements: 
  1. import org.bson.Document;  
  2. import com.mongodb.Block;  
  3. import com.mongodb.client.FindIterable;  
  4.   
  5. import static com.mongodb.client.model.Filters.*;  
  6. import static com.mongodb.client.model.Sorts.ascending;  
  7. import static java.util.Arrays.asList;  
Query for All Documents in a Collection 
To return all documents in a collection, call the find method without a criteria document. For example, the following operation queries for all documents in the restaurants collection. 
  1. FindIterable iterable = db.getCollection("restaurants").find();  
Iterate the results and apply a block to each resulting document. 
  1. iterable.forEach(new Block() {  
  2.     @Override  
  3.     public void apply(final Document document) {  
  4.         System.out.println(document);  
  5.     }  
  6. });  
The result set contains all documents in the restaurants collection. 

Specify Equality Conditions 
With the MongoDB Java driver, use the following code to implement the equalities conditions document: 
  1. new Document( , )  
If the  is in an embedded document or an array, use dot notation to access the field. To help specify the query condition, the Java driver also provides the Filters class. The class contains various static methods to simplify building the query predicates, including the eq method: 
Query by a Top Level Field 
The following operation finds documents whose borough field equals "Manhattan". 
  1. FindIterable iterable = db.getCollection("restaurants").find(  
  2.         new Document("borough""Manhattan"));  
Iterate the results and apply a block to each resulting document. 
  1. iterable.forEach(new Block() {  
  2.     @Override  
  3.     public void apply(final Document document) {  
  4.         System.out.println(document);  
  5.     }  
  6. });  
Using the static Filters helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find(eq("borough""Manhattan"));  
Query by a Field in an Embedded Document 
To specify a condition on a field within an embedded document, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following operation specifies an equality condition on the zipcode field in theaddress embedded document. 
  1. FindIterable iterable = db.getCollection("restaurants").find(  
  2.         new Document("address.zipcode""10075"));  
  3.   
  4. iterable.forEach(new Block() {  
  5.     @Override  
  6.     public void apply(final Document document) {  
  7.         System.out.println(document);  
  8.     }  
  9. });  
Using the static Filters helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find(eq("address.zipcode""10075"));  
For more information on querying on fields within an embedded document, see Embedded Documents

Query by a Field in an Array 
The grades array contains embedded documents as its elements. To specify a condition on a field in these documents, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following queries for documents whose grades array contains an embedded document with a field grade equal to "B". 
  1. FindIterable iterable = db.getCollection("restaurants").find(  
  2.         new Document("grades.grade""B"));  
  3.   
  4. iterable.forEach(new Block() {  
  5.     @Override  
  6.     public void apply(final Document document) {  
  7.         System.out.println(document);  
  8.     }  
  9. });  
Using the static Filters helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find(eq("grades.grade""B"));  
For more information on querying on arrays, such as specifying multiple conditions on array elements, see Arrays and $elemMatch

Specify Conditions with Operators 
MongoDB provides operators to specify query conditions, such as comparison operators. Although there are some exceptions, such as the $or and $and conditional operators, query conditions using operators generally have the following form: 
  1. new Document( new Document( , ) )  
To help specify the query condition, the Java driver also provides the Filters class. The class contains various static methods to simplify building the query predicates, including the lt (less than) and gt (greater than) methods: 
  1. lt(, )  
  2. gt(, )  
Greater Than Operator ($gt) 
Query for documents whose grades array contains an embedded document with a field score greater than 30. 
  1. FindIterable iterable = db.getCollection("restaurants").find(  
  2.         new Document("grades.score"new Document("$gt"30)));  
  3.   
  4. iterable.forEach(new Block() {  
  5.     @Override  
  6.     public void apply(final Document document) {  
  7.         System.out.println(document);  
  8.     }  
  9. });  
Using the static Filters helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find(gt("grades.score"30));  
Less Than Operator ($lt) 
Query for documents whose grades array contains an embedded document with a field score less than 10. 
  1. FindIterable iterable = db.getCollection("restaurants").find(  
  2.         new Document("grades.score"new Document("$lt"10)));  
  3.   
  4. iterable.forEach(new Block() {  
  5.     @Override  
  6.     public void apply(final Document document) {  
  7.         System.out.println(document);  
  8.     }  
  9. });  
Using the static Filters helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find(lt("grades.score"10));  
Combine Conditions 
You can combine multiple query conditions in logical conjunction (AND) and logical disjunctions (OR). 

Logical AND 
You can specify a logical conjunction (AND) for multiple query conditions by appending conditions to the query document. See the append method in the org.bson.Document class. 
  1. FindIterable iterable = db.getCollection("restaurants").find(  
  2.         new Document("cuisine""Italian").append("address.zipcode""10075"));  
  3.   
  4. iterable.forEach(new Block() {  
  5.     @Override  
  6.     public void apply(final Document document) {  
  7.         System.out.println(document);  
  8.     }  
  9. });  
The result set includes only the documents that matched all specified criteria. Using the static Filters helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find(and(eq("cuisine""Italian"), eq("address.zipcode""10075")));  
Logical OR 
You can specify a logical disjunction (OR) for a list of query conditions by using the $or query operator. 
  1. FindIterable iterable = db.getCollection("restaurants").find(  
  2.         new Document("$or", asList(new Document("cuisine""Italian"),  
  3.                 new Document("address.zipcode""10075"))));  
  4.   
  5. iterable.forEach(new Block() {  
  6.     @Override  
  7.     public void apply(final Document document) {  
  8.         System.out.println(document);  
  9.     }  
  10. });  
The result set includes only the documents that match either conditions. Using the static Filters helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find(or(eq("cuisine""Italian"), eq("address.zipcode""10075")));  
Sort Query Results 
To specify an order for the result set, append the sort() method to the query. Pass to sort() method a document which contains the field(s) to sort by and the corresponding sort type, e.g. 1 for ascending and -1 for descending

For example, the following operation returns all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the "address.zipcode" field in ascending order: 
  1. FindIterable iterable = db.getCollection("restaurants").find()  
  2.         .sort(new Document("borough"1).append("address.zipcode"1));  
  3.   
  4. iterable.forEach(new Block() {  
  5.     @Override  
  6.     public void apply(final Document document) {  
  7.         System.out.println(document);  
  8.     }  
  9. });  
Using the static Sorts helper(s), you can also specify the query as follows: 
  1. db.getCollection("restaurants").find().sort(ascending("borough""address.zipcode"));  
The operation returns the results sorted in the specified order. 

Additional Information 
In the Java Driver documentation, see findFiltersFindIterableBlock, and sort; In the MongoDB Manual, see also Query Documents tutorialProjection tutorialQuery and Projection Operators reference, and Cursor Methods

Supplement 
Getting Started - Insert Data with Java Driver 
Getting Started - Update Data with Java Driver

沒有留言:

張貼留言

[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...