`
baobeituping
  • 浏览: 1041936 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

MongoDB 3.0查询

 
阅读更多

Find or Query Data with Java Driver

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

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;

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.

FindIterable<Document> iterable = db.getCollection("restaurants").find();

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

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:

new Document( <field>, <value> )

If the <field> 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:

eq(<field>, <value>)

Query by a Top Level Field

The following operation finds documents whose borough field equals "Manhattan".

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("borough", "Manhattan"));

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

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 notationrequires quotes around the whole dotted field name. The following operation specifies an equality condition on the zipcode field in the address embedded document.

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("address.zipcode", "10075"));

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

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

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("grades.grade", "B"));

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

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:

new Document( <field>, new Document( <operator>, <value> ) )

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:

lt(<field>, <value>)
gt(<field>, <value>)

Greater Than Operator ($gt)

Query for documents whose grades array contains an embedded document with a field score greater than 30.

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("grades.score", new Document("$gt", 30)));

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

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.

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("grades.score", new Document("$lt", 10)));

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

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.

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("cuisine", "Italian").append("address.zipcode", "10075"));

The result set includes only the documents that matched all specified criteria.

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

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.

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("$or", asList(new Document("cuisine", "Italian"),
                new Document("address.zipcode", "10075"))));

The result set includes only the documents that match either conditions.

Iterate the results and apply a block to each resulting document.

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

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:

FindIterable<Document> iterable = db.getCollection("restaurants").find()
        .sort(new Document("borough", 1).append("address.zipcode", 1));

Iterate the results and apply a block to each resulting document

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

Using the static Filters helper(s), you can also specify the query as follows:

db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics