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:
- import org.bson.Document;
- import com.mongodb.Block;
- import com.mongodb.client.FindIterable;
- import static com.mongodb.client.model.Filters.*;
- import static com.mongodb.client.model.Sorts.ascending;
- import static java.util.Arrays.asList;
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.
- FindIterable
iterable = db.getCollection( "restaurants").find();
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
Specify Equality Conditions
With the MongoDB Java driver, use the following code to implement the equalities conditions document:
- new Document(
, )
- eq(
, )
The following operation finds documents whose borough field equals "Manhattan".
- FindIterable
iterable = db.getCollection( "restaurants").find( - new Document("borough", "Manhattan"));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find(eq("borough", "Manhattan"));
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.
- FindIterable
iterable = db.getCollection( "restaurants").find( - new Document("address.zipcode", "10075"));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
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".
- FindIterable
iterable = db.getCollection( "restaurants").find( - new Document("grades.grade", "B"));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find(eq("grades.grade", "B"));
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:
- new Document(
, new Document(, ) )
- lt(
, ) - gt(
, )
Query for documents whose grades array contains an embedded document with a field score greater than 30.
- FindIterable
iterable = db.getCollection( "restaurants").find( - new Document("grades.score", new Document("$gt", 30)));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find(gt("grades.score", 30));
Query for documents whose grades array contains an embedded document with a field score less than 10.
- FindIterable
iterable = db.getCollection( "restaurants").find( - new Document("grades.score", new Document("$lt", 10)));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find(lt("grades.score", 10));
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.
- FindIterable
iterable = db.getCollection( "restaurants").find( - new Document("cuisine", "Italian").append("address.zipcode", "10075"));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
You can specify a logical disjunction (OR) for a list of query conditions by using the $or query operator.
- FindIterable
iterable = db.getCollection( "restaurants").find( - new Document("$or", asList(new Document("cuisine", "Italian"),
- new Document("address.zipcode", "10075"))));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find(or(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
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:
- FindIterable
iterable = db.getCollection( "restaurants").find() - .sort(new Document("borough", 1).append("address.zipcode", 1));
- iterable.forEach(new Block
() { - @Override
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));
Additional Information
In the Java Driver documentation, see find, Filters, FindIterable, Block, and sort; In the MongoDB Manual, see also Query Documents tutorial, Projection tutorial, Query and Projection Operators reference, and Cursor Methods.
Supplement
* Getting Started - Insert Data with Java Driver
* Getting Started - Update Data with Java Driver
沒有留言:
張貼留言