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"));
相关推荐
spring MVC 5.0M4 MongoDB3.0 log4j2 注解 等等...
本项目以spring4.0+mongodb3.0为基础开发简易demo,对mongodb进行权限认证,简单增删改查,mapreduce,aggregate操作简单演示,java项目,非maven项目,使用之前先配好mongodb及其修改mongodb.properties里参数。
详细描述MongoDB 安装步骤以及中途遇到的问题解决
mongodb 3.0 suse11 64bit 64位 安装包 release 版本 效率提升不是一点点
NULL 博文链接:https://jcs130.iteye.com/blog/2236163
近期学习MongoDb 需要查看API,可是官方只能从浏览器查询,没有办法下载,并且程序安装包中也没有docs。让我很是纠结,该文件是我自己爬虫、打包并制作成CHM贡献给大家。
可以试用30天,到期之后运行bat再次试用。注意保存配置
这是mongdb3.0.8在linux版本的压缩包
此资源在mogoDB官网下载,为2016年9月份最新版本,64位。 ...robomongo是作为mogoDB数据库的可视化工具,你可以理解成SQL,MYSQL,里面能用鼠标控制的操作。 该robomongo版本是0.9.0,能支持最新的mongo3.x,...
通过安装当前版本3.0.4的MongoDB,在hpess / chef映像上构建。 具有简单的副本集支持。用根据我们所有其他容器,一个简单的docker compose文件将使您轻松轻松地建立一个实例。 这将启动一个绑定到默认mongo端口的...
主要介绍了使用spring连接及操作mongodb3.0实例,详细的介绍了使用spring的情况下,在java中简单操作mongodb。有兴趣的可以了解一下。
ansible-mongodb Ansible playbook 和用于配置简单 MongoDB(包括 MongoDB 3.0)的示例。 这对于想要深入了解 MongoDB(尤其是 3.0)并能够轻松(重新)创建环境的人们来说(目前)是很好的。要求Ansible (1.8.x) ...
MongoDB 3.0 安全权限访问控制,在添加用户上面3.0版本和之前的版本有很大的区别,这里就说明下3.0的添加用户的方法。由于这版本改变的有些大,解决了很久,终于解决,下面把解决的步骤以及思路分享给大家。
Spring Data MongoDB API。 Spring Data MongoDB 开发文档。
linux版本mongodb换件搭建部署,设置开机自启动,数据库的导入导出例子
亲测可用, NoSQL Manager for MongoDB 2.7.x, 支持MongoDB 3.0, 下载运行 破解.bat即可
注意 管理您的笔记的 grails 2.2.4 应用程序。 它使用 MongoDB 3.0 作为其存储库。 您可以通过使用 username:user 密码:user 登录来测试应用程序
开源数据库mongodb, mongodb-win32-x86_x64-2008plus-3.0.9, 亲测可用。具体使用,清参考windows下安装说明。 注意安装的时候,要预留4G左右的磁盘可用空间,初始化的时候,需要检测的。
官方发布的mongodb3.0安装包,适用于linux及centos系统。