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框架下集成MongoDB 3.0数据库,同时利用log4j2进行日志管理,并且运用注解进行程序的简化与优化。下面将对这些核心知识点进行详细阐述。 首先,Spring MVC是Spring...
本教程主要针对MongoDB 3.0版本,结合Java进行实战教学。 在Java中使用MongoDB,我们需要依赖MongoDB的Java驱动程序,即`mongo-java-driver`。这个驱动程序提供了一套丰富的API,允许开发者在Java应用中方便地连接...
本项目以spring4.0+mongodb3.0为基础开发简易demo,对mongodb进行权限认证,简单增删改查,mapreduce,aggregate操作简单演示,java项目,非maven项目,使用之前先配好mongodb及其修改mongodb.properties里参数。
在“mongoDB3.0以上连接工具.zip”这个压缩包中,我们可以找到用于连接MongoDB 3.0及以上版本的工具,这些工具可能包括MongoDB Compass、Robo 3T (原名Robomongo)、MongoDB Shell等。这些工具都是为了帮助用户更高效...
在SUSE Linux Enterprise Server 11(SLES11)64位操作系统上安装MongoDB 3.0版本,可以充分利用64位系统的内存资源,提供更优的性能和稳定性。以下是关于MongoDB 3.0在SUSE11 64bit环境下安装和使用的详细步骤及...
2015.3.3正式发布了Mongodb3.0,对比2.0版本加入了许多新特性,主要加了新的存储引擎WiredTiger,默认引擎是MMAP;本文档主要讲述的是MongoDB 3.0数据压缩测试;感兴趣的朋友可以过来看看
在这个“mongodb3.0Linux版本的tgz包”中,我们主要讨论的是MongoDB 3.0.8在Linux操作系统上的部署和使用。 MongoDB 3.0是其发展中的一个重要里程碑,它引入了许多新特性,提高了性能和可扩展性。以下是一些关键...
### MongoDB 3.0 数据压缩测试分析 #### MongoDB 3.0 新特性概览 MongoDB 3.0 是在2015年3月3日正式发布的,与之前的2.0版本相比,它引入了大量的新功能和技术改进。其中最重要的一个特性就是加入了新的存储引擎...
近期学习MongoDb 需要查看API,可是官方只能从浏览器查询,没有办法下载,并且程序安装包中也没有docs。让我很是纠结,该文件是我自己爬虫、打包并制作成CHM贡献给大家。
6. **新命令和查询优化器**:MongoDB 3.0引入了新的查询优化器,能更好地选择执行计划,同时增加了一些新的数据库命令,如`collStats`,用于收集集合统计信息。 在安装MongoDB 3.0时,对于RHEL62或CentOS系统,你...
此资源在mogoDB官网下载,为2016年9月份最新版本,64位。 ...robomongo是作为mogoDB数据库的可视化工具,你可以理解成SQL,MYSQL,里面能用鼠标控制的操作。 该robomongo版本是0.9.0,能支持最新的mongo3.x,...
通过安装当前版本3.0.4的MongoDB,在hpess / chef映像上构建。 具有简单的副本集支持。用根据我们所有其他容器,一个简单的docker compose文件将使您轻松轻松地建立一个实例。 这将启动一个绑定到默认mongo端口的...
在本文中,我们将探讨如何使用Spring连接并操作MongoDB 3.0版本。 首先,我们需要在项目中引入相应的依赖。在Maven项目中,这通常通过在pom.xml文件中添加依赖来完成。在提供的内容中,我们可以看到以下关键依赖: ...
MongoDB 3.0引入了更强大的安全权限访问控制,以增强数据库的安全性。相比于之前的版本,这个新特性对用户管理进行了重大改进,确保只有经过身份验证和授权的用户才能执行特定的操作。以下是对MongoDB 3.0安全权限...
ansible-mongodb Ansible playbook 和用于配置简单 MongoDB(包括 MongoDB 3.0)的示例。 这对于想要深入了解 MongoDB(尤其是 3.0)并能够轻松(重新)创建环境的人们来说(目前)是很好的。要求Ansible (1.8.x) ...
Spring Data MongoDB API。 Spring Data MongoDB 开发文档。
### Linux版MongoDB环境搭建详解 #### 一、前言 MongoDB 是一款非常流行的开源文档型数据库系统,因其灵活性和高性能而广泛应用于各种场景。本文档将详细介绍如何在Linux环境下搭建MongoDB运行环境,包括从创建...
MongoDB的源码是开放的,这意味着你可以探索其内存管理、数据存储、查询解析等方面的细节,这对于数据库开发和优化具有重要意义。 总的来说,"mongodb-src-r3.0.3.zip" 提供了一个学习和定制MongoDB的宝贵资源,...
亲测可用, NoSQL Manager for MongoDB 2.7.x, 支持MongoDB 3.0, 下载运行 破解.bat即可