Query Documents using Document ID in MongoDB – 在MongoDB中使用文档ID查询文档

最后修改: 2022年 7月 18日

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

1. Overview

1.概述

In this tutorial, we’ll look at performing query operations using the Document ID in MongoDB. MongoDB provides a find operator to query documents from a collection.

在本教程中,我们将了解如何在MongoDB中使用文档 ID 执行查询操作。MongoDB 提供了一个find操作符来从集合中查询文档。

In this tutorial, we’ll first look at querying documents using Document ID in the MongoDB Shell query and then use the Java driver code.

在本教程中,我们将首先了解在MongoDB Shell查询中使用Document ID查询文档,然后使用Java驱动代码。

2. What Is the Document ID of a MongoDB Document?

2.什么是MongoDB文档的文档ID?

Just like any other database management system, MongoDB requires a unique identifier for each document stored in a collection. This unique identifier acts as a primary key to the collection.

就像其他数据库管理系统一样,MongoDB要求为存储在集合中的每个文档提供一个唯一的标识符。这个唯一的标识符作为集合的一个主键。

In MongoDB, the ID is composed of 12 bytes:

在MongoDB中,ID是由12个字节组成的。

  • a 4-byte timestamp that represents ID’s creation measured in seconds since the Unix epoch
  • a 5-byte random generated value that is unique to the machine and process
  • a 3-byte incrementing counter

In MongoDB, the ID is stored in a field named _id and is generated by the client. Hence, the ID should be generated before sending the document to the database. On the client side, we can either use a driver-generated ID or generate a custom ID.

在MongoDB中,ID存储在一个名为_id的字段中,并由客户端生成。因此,在将文档发送到数据库之前应生成ID。在客户端,我们可以使用驱动程序生成的ID,或者生成一个自定义ID。

The unique identifier is stored in the ObjectId class. This class provides convenience methods to get data stored in the ID without actually parsing it. MongoDB will add the _id field and assign a unique ObjectId for the document if the _id is not specified while inserting documents.

唯一的标识符被存储在ObjectId类中。这个类提供了方便的方法来获取存储在ID中的数据,而不需要实际解析它。如果在插入文档时没有指定_id字段,MongoDB将添加_id字段并为文档分配一个唯一的ObjectId

3. Database Initialization

3.数据库初始化

Firstly, let’s set up a new database baeldung and a sample collection, vehicle:

首先,让我们建立一个新的数据库baeldung和一个样本集,vehicle

use baeldung;
db.createCollection("vehicle");

Further, let’s add a few documents into the collection by using the insertMany method:

此外,让我们通过使用insertMany方法在集合中添加一些文档。

db.vehicle.insertMany([
{
    "companyName":"Skoda", 
    "modelName":"Octavia",
    "launchYear":2016,
    "type":"Sports",
    "registeredNo":"SKO 1134"
},
{ 
    "companyName":"BMW",
    "modelName":"X5",
    "launchYear":2020,
    "type":"SUV",
    "registeredNo":"BMW 3325"
},
{
    "companyName":"Mercedes",
    "modelName":"Maybach",
    "launchYear":2021,
    "type":"Luxury",
    "registeredNo":"MER 9754"
}]);

In case of successful insertion, the above command will print a JSON similar to the one shown below:

在插入成功的情况下,上述命令将打印一个类似于下图的JSON。

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("62d01d17cdd1b7c8a5f945b9"),
        ObjectId("62d01d17cdd1b7c8a5f945ba"),
        ObjectId("62d01d17cdd1b7c8a5f945bb")
    ]
}

We have successfully set up the database and collection. We’ll use this database and collection for all the examples.

我们已经成功地设置了数据库和集合。我们将在所有的例子中使用这个数据库和集合。

4. Using the MongoDB Shell

4.使用MongoDB Shell

We will make use of the db.collection.find(query, projection) method to query documents from MongoDB.

我们将利用db.collection.find(query, projection)方法来查询MongoDB中的文档。

Firstly, let’s write a query that would return all the vehicle collection documents:

首先,让我们写一个查询,返回所有的vehicle集合文档。

db.vehicle.find({});

The above query returns all the documents:

上述查询返回所有的文件。

{ "_id" : ObjectId("62d01d17cdd1b7c8a5f945b9"), "companyName" : "Skoda",
    "modelName" : "Octavia", "launchYear" : 2016, "type" : "Sports", "registeredNo" : "SKO 1134" }
{ "_id" : ObjectId("62d01d17cdd1b7c8a5f945ba"), "companyName" : "BMW",
    "modelName" : "X5", "launchYear" : 2020, "type" : "SUV", "registeredNo" : "BMW 3325" }
{ "_id" : ObjectId("62d01d17cdd1b7c8a5f945bb"), "companyName" : "Mercedes",
    "modelName" : "Maybach", "launchYear" : 2021, "type" : "Luxury", "registeredNo" : "MER 9754" }

Further, let’s write a query to fetch the vehicle collection document using the ID returned in the results above:

此外,让我们写一个查询,使用上面结果中返回的ID来获取vehicle集合文档。

db.vehicle.find(
{
    "_id": ObjectId("62d01d17cdd1b7c8a5f945b9")
});

The above query returns vehicle collection document with _id equal to ObjectId(“62d01d17cdd1b7c8a5f945b9”):

上述查询返回vehicle集合文档,_id等于ObjectId(“62d01d17cdd1b7c8a5f945b9”)

{ "_id" : ObjectId("62d01d17cdd1b7c8a5f945b9"), "companyName" : "Skoda",
    "modelName" : "Octavia", "launchYear" : 2016, "type" : "Sports", "registeredNo" : "SKO 1134" }

Moreover, we can retrieve multiple vehicle collection documents using IDs with the in query operator:

此外,我们可以通过in查询操作符使用ID检索多个vehicle集合文件。

db.vehicle.find(
{
    "_id": {
        $in: [
            ObjectId("62d01d17cdd1b7c8a5f945b9"),
            ObjectId("62d01d17cdd1b7c8a5f945ba"),
            ObjectId("62d01d17cdd1b7c8a5f945bb")
        ]
    }
});

The above query returns all vehicle collection documents for the queried IDs in the in operator:

上述查询返回in运算符中被查询ID的所有vehicle集合文件。

{ "_id" : ObjectId("62d01d17cdd1b7c8a5f945b9"), "companyName" : "Skoda",
    "modelName" : "Octavia", "launchYear" : 2016, "type" : "Sports", "registeredNo" : "SKO 1134" }
{ "_id" : ObjectId("62d01d17cdd1b7c8a5f945ba"), "companyName" : "BMW",
    "modelName" : "X5", "launchYear" : 2020, "type" : "SUV", "registeredNo" : "BMW 3325" }
{ "_id" : ObjectId("62d01d17cdd1b7c8a5f945bb"), "companyName" : "Mercedes",
    "modelName" : "Maybach", "launchYear" : 2021, "type" : "Luxury", "registeredNo" : "MER 9754" }

Likewise, any of the query operators can be used as a filter for the find() method with IDs to be queried.

同样,任何一个查询运算符都可以作为find()方法的过滤器,并带有要查询的ID。

Also, it is important to note that while querying documents with the _id field, the Document ID string value should be specified as an ObjectId() and not a String.

另外,需要注意的是,在用_id字段查询文档时,文档ID字符串值应被指定为ObjectId(),而不是String

Let’s try to query an existing document with ID as a String value:

让我们尝试查询一个现有的ID为String值的文档。

db.vehicle.find(
{
    "_id": "62d01d17cdd1b7c8a5f945b9"
});

Unfortunately, the above query would not return any documents as there does not exist any document with ID as String value 62d01d17cdd1b7c8a5f945b9.

不幸的是,上述查询不会返回任何文件,因为不存在任何ID为String值的文件62d01d17cdd1b7c8a5f945b9

5. Using the Java Driver

5.使用Java驱动

So far, we’ve learned how to query documents using ID with the MongoDB Shell. Let’s now implement the same using the MongoDB Java driver.

到目前为止,我们已经学会了如何使用MongoDB Shell的ID来查询文档。现在让我们使用MongoDB的Java驱动实现同样的功能。

Before performing the update operation, let’s first connect to the vehicle collection in the baeldung database:

在执行更新操作之前,让我们首先连接到baeldung数据库中的vehicle集合。

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

Here, in this case, we are connecting to MongoDB, which is running at default port 27017 on localhost.

在这里,在这种情况下,我们要连接到MongoDB,它运行在本地主机的默认端口27017。

Firstly, let’s write the code to query documents using ID:

首先,让我们编写代码,使用ID查询文档。

Bson filter = Filters.eq("_id", new ObjectId("62d01d17cdd1b7c8a5f945b9"));
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 with the _id field to query. The above snippet would return vehicle collection document where the _id equals ObjectId(“62d01d17cdd1b7c8a5f945b9”).

在这里,我们将一个Bson过滤器作为参数传递给find()方法,并在_id字段中查询。上面的片段将返回vehicle集合文档,其中_id等于ObjectId(“62d01d17cdd1b7c8a5f945b9”)

Further, let’s write a snippet to query documents with multiple IDs:

此外,让我们写一个片段来查询具有多个ID的文档。

Bson filter = Filters.in("_id", new ObjectId("62d01d17cdd1b7c8a5f945b9"),
  new ObjectId("62d01d17cdd1b7c8a5f945ba"));
FindIterable<Document> documents = collection.find(filter);

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

The above query returns all vehicle collection documents for the queried IDs.

上述查询返回被查询的ID的所有vehicle集合文档。

Finally, let’s try to query the vehicle collection with a driver-generated ID:

最后,让我们尝试用一个司机生成的ID来查询vehicle集合。

Bson filter = Filters.eq("_id", new ObjectId());
FindIterable<Document> documents = collection.find(filter);

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

The above query would not return any documents as a document with the newly generated ID would not exist in the vehicle collection.

上述查询不会返回任何文件,因为在vehicle集合中不存在一个新生成的ID的文件。

6. Conclusion

6.结语

In this article, we’ve learned to query documents using Document ID in MongoDB. At first, we looked into these use cases in the MongoDB Shell query, and then we discussed the corresponding Java driver code.

在这篇文章中,我们已经学会了在MongoDB中使用Document ID来查询文档。首先,我们研究了MongoDB Shell查询中的这些用例,然后我们讨论了相应的Java驱动代码。

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

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