Mongodb 3.2 Java 显示指定字段 条件查询 官方
2017-01-05 21:21
936 查看
MongoDB Driver
Tutorials
Read Operations
Find operations retrieve documents from a collection. You can specify a filter to select only those documents that match the filter condition.
The example below requires a
in the
Include the following import statements:
Include the following code which the examples in the tutorials will use to print the results of the find operations:
Connect to a MongoDB deployment and declare and define a
For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port
define
and
For additional information on connecting to MongoDB, see Connect to MongoDB.
To query the collection, you can use the collection’s
You can call the method without any arguments to query all documents in a collection:
Or pass a filter to query for documents that match the filter criteria:
To query for documents that match certain conditions, pass a filter document to the
To specify an empty filter (i.e. match all documents in a collection), use an empty
TIP
For the
you can also call the method without passing a filter object to match all documents in a collection.
To facilitate the creation of filter documents, the Java driver provides the
that provides filter condition helper methods.
Consider the following
specifies that:
the
2 and less than 5, AND
the
if
an element):
The following example specifies the same filter condition using the
methods:
For a list of MongoDB query filter operators, refer to the MongoDB Manual. For the associated
see
See also the Query Documents Tutorial for an overview of querying in MongoDB, including specifying filter
conditions on arrays and embedded documents.
The
returns an instance of the
The interface provides various methods that you can chain to the
the output or behavior of the query, such as
as well as for iterating the results, such as
By default, queries in MongoDB return all fields in matching documents. To specify the fields to return in the matching documents, you can specify a projection
document.
Consider the following
specifies that the matching documents return only the
and the
To facilitate the creation of projection documents, the Java driver provides the
In the projection document, you can also specify a projection expression using a projection
operator
For an example on using the
see the Text Search tutorial.
To sort documents, pass a sort specification document to the
The Java driver provides
to facilitate the sort specification document.
The
themselves return
to the
The
provides helper methods to access the results of an operation:
For read operations on replica sets or sharded
clusters, applications can configure the read preference at three levels:
In a
Via
Via
as in the following example:
In a
its
In a
its
are immutable. Calling
returns a new instance and does not affect the instance on which the method is called.
For example, in the following, the
of primaryPreferred whereas the read preference of the
For read operations on replica sets or sharded
clusters, applications can configure the read concern at three levels:
In a
Via
as in the following example:
Via
as in the following example:
In a
its
as in the following example:
In a
its
as in the following example:
are immutable. Calling
returns a new instance and does not affect the instance on which the method is called.
For example, in the following, the
whereas the read concern of the
You can build
or
concern.
For example, the following sets all three at the collection level:
Tutorials
Read Operations
Find Operations
Find operations retrieve documents from a collection. You can specify a filter to select only those documents that match the filter condition.
Prerequisites
The example below requires a restaurantscollection
in the
testdatabase. To create and populate the collection, follow the directions in github.
Include the following import statements:
import com.mongodb.*; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Projections; import com.mongodb.client.model.Filters; import static com.mongodb.client.model.Filters.*; import static com.mongodb.client.model.Projections.*; import com.mongodb.client.model.Sorts; import java.util.Arrays; import org.bson.Document;
Include the following code which the examples in the tutorials will use to print the results of the find operations:
Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } };
Connect to a MongoDB Deployment
Connect to a MongoDB deployment and declare and define a MongoDatabaseinstance and a
MongoCollectioninstance
For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port
27017and
define
databaseto refer to the
testdatabase
and
collectionto refer to the
restaurantscollection:
MongoClient mongoClient = new MongoClient(); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("restaurants");
For additional information on connecting to MongoDB, see Connect to MongoDB.
Query a Collection
To query the collection, you can use the collection’s find()method.
You can call the method without any arguments to query all documents in a collection:
collection.find().forEach(printBlock);
Or pass a filter to query for documents that match the filter criteria:
collection.find(eq("name", "456 Cookies Shop")) .forEach(printBlock);
Query Filters
To query for documents that match certain conditions, pass a filter document to the find()method.
Empty Filter
To specify an empty filter (i.e. match all documents in a collection), use an empty Documentobject.
collection.find(new Document()).forEach(printBlock);
TIP
For the
find()method,
you can also call the method without passing a filter object to match all documents in a collection.
collection.find().forEach(printBlock);
Filters
Helper
To facilitate the creation of filter documents, the Java driver provides the Filtersclass
that provides filter condition helper methods.
Consider the following
findoperation which includes a filter
Documentwhich
specifies that:
the
starsfield is greater than or equal to
2 and less than 5, AND
the
categoriesfield equals
"Bakery"(or
if
categoriesis an array, contains the string
"Bakery"as
an element):
collection.find( new Document("stars", new Document("$gte", 2) .append("$lt", 5)) .append("categories", "Bakery")).forEach(printBlock);
The following example specifies the same filter condition using the
Filtershelper
methods:
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) .forEach(printBlock);
For a list of MongoDB query filter operators, refer to the MongoDB Manual. For the associated
Filtershelpers,
see
Filters.
See also the Query Documents Tutorial for an overview of querying in MongoDB, including specifying filter
conditions on arrays and embedded documents.
FindIterable
The find()method
returns an instance of the
FindIterableinterface.
The interface provides various methods that you can chain to the
find()method to modify
the output or behavior of the query, such as
sort()or
projection(),
as well as for iterating the results, such as
iterator()and
forEach().
Projections
By default, queries in MongoDB return all fields in matching documents. To specify the fields to return in the matching documents, you can specify a projectiondocument.
Consider the following
findoperation which includes a projection
Documentwhich
specifies that the matching documents return only the
namefield,
starsfield,
and the
categoriesfield.
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) .projection(new Document("name", 1) .append("stars", 1) .append("categories",1) .append("_id", 0)) .forEach(printBlock);
To facilitate the creation of projection documents, the Java driver provides the
Projectionsclass.
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) .projection(fields(include("name", "stars", "categories"), excludeId())) .forEach(printBlock);
In the projection document, you can also specify a projection expression using a projection
operator
For an example on using the
Projections.metaTextScore,
see the Text Search tutorial.
Sorts
To sort documents, pass a sort specification document to the FindIterable.sort()method.
The Java driver provides
Sortshelpers
to facilitate the sort specification document.
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) .sort(Sorts.ascending("name")) .forEach(printBlock);
Sort with Projections
The FindIterablemethods
themselves return
FindIterableobjects, and as such, you can append multiple
FindIterablemethods
to the
find()method.
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) .sort(Sorts.ascending("name")) .projection(fields(include("name", "stars", "categories"), excludeId())) .forEach(printBlock);
MongoIterable
The MongoIterableinterface
provides helper methods to access the results of an operation:
iterator()
first()
forEach()
map()
into()
Read Preference
For read operations on replica sets or shardedclusters, applications can configure the read preference at three levels:
In a
MongoClient()
Via
MongoClientOptions:
MongoClientOptions options = MongoClientOptions.builder().readPreference( ReadPreference.secondary()).build(); MongoClient mongoClient = new MongoClient(Arrays.asList( new ServerAddress("host1", 27017), new ServerAddress("host2", 27017)), options);
Via
MongoClientURI,
as in the following example:
MongoClient mongoClient = new MongoClient( new MongoClientURI("mongodb://host1:27017,host2:27017/?readPreference=secondary"));
In a
MongoDatabasevia
its
withReadPreferencemethod.
MongoDatabase database = mongoClient.getDatabase("test") .withReadPreference(ReadPreference.secondary());
In a
MongoCollectionvia
its
withReadPreferencemethod:
MongoCollection<Document> collection = database.getCollection("restaurants") .withReadPreference(ReadPreference.secondary());
MongoDatabaseand
MongoCollectioninstances
are immutable. Calling
.withReadPreference()on an existing
MongoDatabaseor
MongoCollectioninstance
returns a new instance and does not affect the instance on which the method is called.
For example, in the following, the
collectionWithReadPrefinstance has the read preference
of primaryPreferred whereas the read preference of the
collectionis unaffected.
MongoCollection<Document> collectionWithReadPref = collection.withReadPreference(ReadPreference.primaryPreferred());
Read Concern
For read operations on replica sets or shardedclusters, applications can configure the read concern at three levels:
In a
MongoClient()
Via
MongoClientURI,
as in the following example:
MongoClient mongoClient = new MongoClient( new MongoClientURI("mongodb://host1:27017,host2:27017/?readConcernLevel=majority"));
Via
MongoClientOptions,
as in the following example:
MongoClientOptions options = MongoClientOptions.builder().readConcern(ReadConcern.DEFAULT).build(); MongoClient mongoClient = new MongoClient(Arrays.asList( new ServerAddress("host1", 27017), new ServerAddress("host1", 27017)), options);
In a
MongoDatabasevia
its
withReadConcernmethod,
as in the following example:
MongoDatabase database = mongoClient.getDatabase("test") .withReadConcern(ReadConcern.DEFAULT);
In a
MongoCollectionvia
its
withReadConcernmethod,
as in the following example:
MongoCollection<Document> collection = database.getCollection("restaurants") .withReadConcern(ReadConcern.DEFAULT);
MongoDatabaseand
MongoCollectioninstances
are immutable. Calling
.withReadConcern()on an existing
MongoDatabaseor
MongoCollectioninstance
returns a new instance and does not affect the instance on which the method is called.
For example, in the following, the
collWithReadConcerninstance has majority read concern
whereas the read concern of the
collectionis unaffected.
MongoCollection<Document> collWithReadConcern = collection .withReadConcern(ReadConcern.MAJORITY);
You can build
MongoClientOptions,
MongoDatabase,
or
MongoCollectionto include a combination of read concern, read preference, and write
concern.
For example, the following sets all three at the collection level:
collection = database.getCollection("restaurants") .withReadPreference(ReadPreference.primary()) .withReadConcern(ReadConcern.MAJORITY) .withWriteConcern(WriteConcern.MAJORITY);
相关文章推荐
- Mongodb 3.2 Java 显示指定字段 条件查询 分页排序
- Mongodb 3.4 Java 显示指定字段、 条件查询 官方手册
- MongoDB java 3.2版本查询指定列和排序的补充
- mongodb查询只显示指定字段
- MongoDB官方C#驱动中查询条件Query用法
- Java MongoDB 条件查询及其分组查询
- MongoDB官方C#驱动中查询条件Query用法
- MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询
- java 操作mongodb查询条件的常用设置
- SQL Server 2000通用分页查询存储过程(可指定返回字段,查询条件)
- Mongodb查询指定字段方法
- MongoDB官方C#驱动中查询条件Query用法
- java调用MongodbAPI条件查询
- MongoDB官方C#驱动中查询条件Query用法
- java 操作mongodb查询条件的常用设置
- MongoDB官方C#驱动中查询条件Query用法
- 【mongoDB】Java中使用条件操作符进行查询 推荐
- MongoDB中关于查询条件中包含集合中字段的查询
- laravel-mongodb查询条件与字段类型不一致问题
- spring-data-mongodb的同字段索引多条件查询