Guide to Find in MongoDB – MongoDB中的查找指南

最后修改: 2022年 6月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll look at performing search operations to retrieve documents in MongoDB. MongoDB provides a find operator to query documents from a collection. The main purpose of the find operator is to select documents from a collection based on the query condition and return a cursor to the selected documents.

在本教程中,我们将研究如何执行搜索操作以检索MongoDB中的文档。MongoDB 提供了一个 find 操作符来从集合中查询文档。find操作符的主要目的是根据查询条件从集合中选择文档,并返回到所选文档的游标。

In this tutorial, we’ll first look at the find operator in the MongoDB Shell query and then use the Java driver code.

在本教程中,我们将首先看一下MongoDB Shell查询中的find操作符,然后使用Java驱动代码。

2. Database Initialization

2.数据库初始化

Before we move forward to perform the find operations, we first need to set up a database baeldung and a sample collection employee:

在我们继续执行find操作之前,我们首先需要设置一个数据库baeldung和一个样本集合employee

db.employee.insertMany([
{
    "employeeId":"EMP1",
    "name":"Sam", 
    "age":23,
    "type":"Full Time",
    "department":"Engineering"
},
{ 
    "employeeId":"EMP2",
    "name":"Tony",
    "age":31,
    "type":"Full Time",
    "department":"Admin"
},
{
    "employeeId":"EMP3",
    "name":"Lisa",
    "age":42,
    "type":"Part Time",
    "department":"Engineering"
}]);

Upon successful insertion, the above query would return a JSON result similar to the one shown below:

成功插入后,上述查询将返回一个类似于下图的JSON结果。

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("62a88223ff0a77909323a7fa"),
        ObjectId("62a88223ff0a77909323a7fb"),
        ObjectId("62a88223ff0a77909323a7fc")
    ]
}

At this point, we’ve inserted a few documents into our collection to perform various types of find operations.

在这一点上,我们已经在我们的集合中插入了一些文件,以执行各种类型的find操作。

3. Using the MongoDB Shell

3.使用MongoDB Shell

To query documents from a MongoDB collection, we make use of the db.collection.find(query, projection) method. The method accepts two optional parameters – query and projection – as MongoDB BSON documents.

为了从 MongoDB 集合中查询文档,我们使用了 db.collection.find(query, projection) 方法。该方法接受两个可选参数 – queryprojection – 作为 MongoDB BSON 文档。

The query parameter accepts a selection filter with query operators. To retrieve all the documents from the MongoDB collection, we can omit this parameter or pass a blank document.

query参数接受一个带有查询运算符的选择过滤器。要从MongoDB集合中检索所有的文档,我们可以省略这个参数或传递一个空白文档。

Next, the projection parameter is used to specify the fields to return from the matching documents. To return all the fields in the matching document, we can omit this parameter.

接下来,projection参数用于指定要从匹配文档中返回的字段。要返回匹配文档中的所有字段,我们可以省略这个参数。

Further, let’s start with a basic find query that would return all the collection documents:

此外,让我们从一个基本的find查询开始,它将返回所有的集合文档。

db.employee.find({});

The above query will return all the documents from the employee collection:

上述查询将返回employee集合中的所有文件。

{ "_id" : ObjectId("62a88223ff0a77909323a7fa"), "employeeId" : "1", "name" : "Sam", "age" : 23, "type" : "Full Time", "department" : "Engineering" }
{ "_id" : ObjectId("62a88223ff0a77909323a7fb"), "employeeId" : "2", "name" : "Tony", "age" : 31, "type" : "Full Time", "department" : "Admin" }
{ "_id" : ObjectId("62a88223ff0a77909323a7fc"), "employeeId" : "3", "name" : "Ray", "age" : 42, "type" : "Part Time", "department" : "Engineering" }

Next, let’s write a query to return all employees who belong to the “Engineering” department:

接下来,让我们写一个查询,以返回所有属于“工程”部门的雇员。

db.employee.find(
{
    "department":"Engineering"
});

The above query returns all employee collection documents with department equal to “Engineering”:

上述查询返回所有employee集合文件,department等于”Engineering”

{ "_id" : ObjectId("62a88223ff0a77909323a7fa"), "employeeId" : "1", "name" : "Sam", "age" : 23, "type" : "Full Time", "department" : "Engineering" }
{ "_id" : ObjectId("62a88223ff0a77909323a7fc"), "employeeId" : "3", "name" : "Ray", "age" : 42, "type" : "Part Time", "department" : "Engineering" }

Finally, let’s write a query to fetch the name and age of all the employees that belong to the “Engineering” department:

最后,让我们写一个查询,获取属于“工程 “部门的所有员工的姓名年龄

db.employee.find(
{
    "department":"Engineering"
},
{
    "name":1,
    "age":1
});

The above query returns only the name and age fields of the documents matching the query condition:

上述查询只返回符合查询条件的文档的nameage字段。

{ "_id" : ObjectId("62a88223ff0a77909323a7fa"), "name" : "Sam", "age" : 23 }
{ "_id" : ObjectId("62a88223ff0a77909323a7fc"), "name" : "Ray", "age" : 42 }

Notice that the _id field is returned by default in all the documents unless explicitly excluded.

请注意,除非明确排除,否则所有文件中的_id字段都会默认返回。

Also, it’s important to note that the find operator returns a cursor to the documents that match the query filter. The MongoDB Shell automatically iterates the cursor to display up to 20 documents.

另外,需要注意的是,find操作符会返回符合查询过滤器的文档的游标。MongoDB Shell会自动迭代光标以显示多达20个文档。

In addition, the MongoDB Shell provides a findOne() method that returns just one document that satisfies the mentioned query criteria. If multiple documents match, the first document will be returned according to the natural order of documents on the disk:

此外,MongoDB Shell提供了一个findOne()方法,该方法只返回一个满足所述查询条件的文档。如果有多个文档匹配,将根据磁盘上文档的自然顺序返回第一个文档。

db.employee.findOne();

Unlike find(), the above query would return only a single document instead of a cursor:

find()不同的是,上述查询将只返回一个单一的文档,而不是一个游标。

{
    "_id" : ObjectId("62a99e22a849e1472c440bbf"),
    "employeeId" : "EMP1",
    "name" : "Sam",
    "age" : 23,
    "type" : "Full Time",
    "department" : "Engineering"
}

4. Using the Java Driver

4.使用Java驱动

So far, we’ve seen how to use the MongoDB Shell to perform the find operation. Next, let’s implement the same using the MongoDB Java driver. Before we start, let’s first create a MongoClient connection to the employee collection:

到目前为止,我们已经看到如何使用MongoDB Shell来执行find操作。接下来,让我们使用 MongoDB Java 驱动程序实现同样的操作。在开始之前,让我们首先创建一个MongoClient连接到employee集合。

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("employee");

Here, we created a connection to the MongoDB Server running on default port 27017. Next, we obtained an instance of MongoCollection from the MongoDatabase instance created from the connection.

在这里,我们创建了一个连接到运行在默认端口27017的MongoDB服务器。接下来,我们从连接中创建的MongoDatabase实例中获得了MongoCollection的实例。

Firstly, to perform a find operation, we call the find() method on an instance of MongoCollection. Let’s check the code to retrieve all documents from the collection:

首先,为了执行find操作,我们在MongoCollection的一个实例上调用find()方法。让我们检查一下从集合中检索所有文档的代码。

FindIterable<Document> documents = collection.find();
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

Notice that the find() method returns an instance of FindIterable<Document>. We then obtain an instance of MongoCursor by calling the iterator() method of FindIterable. Finally, we iterate over the cursor to retrieve each document.

请注意,find()方法返回一个FindIterable<Document>实例。然后,我们通过调用FindIterable的iterator()方法获得MongoCursor的实例。最后,我们对游标进行迭代以检索每个文档。

Next, let’s add query operators to filter the documents returned from the find operation:

接下来,让我们添加查询运算符来过滤从find操作返回的文档。

Bson filter = Filters.eq("department", "Engineering");
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

Here, we pass a Bson filter as a parameter to the find() method. We can use any combination of the query operators as a filter for the find() method. The above snippet would return all documents where the department equals “Engineering”.

在这里,我们将一个Bson过滤器作为参数传递给find()方法。我们可以使用查询运算符的任何组合作为find()方法的过滤器。上面的片段将返回所有部门等于 “工程 “的文档。

Further, let’s write a snippet that returns only the name and age fields from the documents matching the selection criteria:

此外,让我们编写一个片段,从符合选择标准的文档中只返回姓名年龄字段。

Bson filter = Filters.eq("department", "Engineering");
Bson projection = Projections.fields(Projections.include("name", "age"));
FindIterable<Document> documents = collection.find(filter)
  .projection(projection);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

Here, we call the projection() method on the FindIterable instance. We pass a Bson filter as a parameter to the projection() method. We can include or exclude any fields from the final results using the projection operation. As an alternative to using the MongoDB Driver and Bson directly, please take a look at our guide to Projection in Spring Data MongoDB.

这里,我们在FindIterable实例上调用projection()方法。我们将一个Bson过滤器作为参数传递给projection()方法。我们可以使用projection操作从最终结果中包括或排除任何字段。作为直接使用 MongoDB 驱动程序和 Bson 的替代方法,请查看我们的 Spring Data MongoDB 中的投影指南

Lastly, we can retrieve the first document of the result using the first() method on the FindIterable instance. This returns a single document instead of a MongoCursor instance:

最后,我们可以使用FindIterable实例上的first()方法检索结果的第一个文档。这将返回一个单一的文档,而不是一个MongoCursor实例。

FindIterable<Document> documents = collection.find();
Document document = documents.first();

5. Conclusion

5.总结

In this article, we’ve learned to perform the find operation in MongoDB using various methods. We performed find to retrieve specific documents that match selection criteria using the query operators. In addition, we also learned to perform a projection to determine which fields are returned in the matching documents.

在本文中,我们已经学会了使用各种方法在MongoDB中执行find操作。我们执行了find来检索符合选择标准的特定文档,使用了查询操作符。此外,我们还学习了执行projection以确定在匹配的文档中返回哪些字段。

At first, we looked into the use cases of find operations in the MongoDB Shell query, and then we discussed the corresponding Java driver code.

首先,我们研究了MongoDB Shell查询中find操作的用例,然后我们讨论了相应的Java驱动代码。

The implementations of all these examples and code snippets are available over on GitHub.

所有这些例子和代码片段的实现都可以在GitHub上找到