Retrieve a Value from MongoDB by Its Key Name – 通过键名从MongoDB中检索一个值

最后修改: 2022年 4月 4日

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

1. Overview

1.概述

In this tutorial, we’ll learn how to retrieve a value from MongoDB by key name. We’ll explore various methods of MongoDB, to fetch the key field names of the documents based on applied filters. First, we’ll use the find or findone method to fetch the required data and later use the aggregation method. Here, we’ll write queries both in the MongoDB shell query and Java driver code.

在本教程中,我们将学习如何从MongoDB中按键名检索一个值。我们将探索MongoDB的各种方法,根据应用的过滤器来获取文档的关键字段名。首先,我们将使用findfindone方法来获取所需的数据,随后使用aggregation方法。在这里,我们将在MongoDB的shell查询和Java驱动代码中编写查询。

Let’s look at the different ways to retrieve the value in MongoDB by a field name.

让我们看看在MongoDB中通过字段名检索值的不同方法。

2. Database Initialization

2.数据库初始化

To begin, we need to set up a new database baeldung and a new collection, travel:

首先,我们需要建立一个新的数据库baeldung和一个新的集合,travel

use baeldung;
db.createCollection(travel);

Let’s now add some dummy data into the collection using the insertMany method of MongoDB:

现在让我们使用MongoDB的insertMany方法向集合中添加一些假数据。

db.travel.insertMany([
{ 
    "passengerId":145,
    "passengerName":"Nathan Green",
    "passengerAge":25,
    "sourceStation":"London",
    "destinationStation":"Birmingham",
    "seatType":"Slepper",
    "emailAddress":"nathongreen12@gmail.com"
},
{ 
    "passengerId":148,
    "passengerName":"Kevin Joseph",
    "passengerAge":28,
    "sourceStation":"Manchester",
    "destinationStation":"London",
    "seatType":"Slepper",
    "emailAddress":"kevin13@gmail.com"
},
{ 
    "passengerId":154,
    "passengerName":"Sheldon burns",
    "passengerAge":26,
    "sourceStation":"Cambridge",
    "destinationStation":"Leeds",
    "seatType":"Slepper",
    "emailAddress":"sheldonnn160@gmail.com"
},
{ 
    "passengerId":168,
    "passengerName":"Jack Ferguson",
    "passengerAge":24,
    "sourceStation":"Cardiff",
    "destinationStation":"Coventry",
    "seatType":"Slepper",
    "emailAddress":"jackfergusion9890@gmail.com"
}
]);

The above insertMany query will return the following JSON:

上述insertMany查询将返回以下JSON。

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("623d7f079d55d4e137e47825"),
	ObjectId("623d7f079d55d4e137e47826"),
	ObjectId("623d7f079d55d4e137e47827"),
        ObjectId("623d7f079d55d4e137e47828")
    ]
}

Till now, we have inserted the dummy data into the collection travel.

到现在为止,我们已经在集合travel中插入了假数据。

3. Using the find Method

3.使用find方法

The find method finds and returns documents that match the specified query criteria on the collection. If multiple documents match the condition, then it’ll return all the documents based on the order of documents on the disk. Additionally, in MongoDB, the find method supports parameter projection in the query. If we specify a projection parameter in the find method, it’ll return all documents containing only projection fields.

find方法找到并返回集合上符合指定查询条件的文档。如果有多个文档符合条件,那么它将根据磁盘上文档的顺序返回所有的文档。此外,在MongoDB中,find方法支持查询中的参数投影。如果我们在find方法中指定一个投影参数,它将返回所有只包含投影字段的文档。

One key point to note is that the _id field is always included in the response unless explicitly removed.

需要注意的一个关键点是,_id字段总是包含在响应中,除非明确删除。

To demonstrate, let’s look into the shell query to project a key field:

为了证明这一点,让我们看一下Shell查询来投射一个关键字段。

db.travel.find({},{"passengerId":1}).pretty();

The response to the above query will be:

对上述询问的答复将是。

{ "_id" : ObjectId("623d7f079d55d4e137e47825"), "passengerId" : 145 }
{ "_id" : ObjectId("623d7f079d55d4e137e47826"), "passengerId" : 148 }
{ "_id" : ObjectId("623d7f079d55d4e137e47827"), "passengerId" : 154 }
{ "_id" : ObjectId("623d7f079d55d4e137e47828"), "passengerId" : 168 }

Here, in this query, we simply projected the passengerId. Let’s now look into the key field with the exclusion of _id:

在这里,在这个查询中,我们只是投射了passengerId。现在让我们看看排除了_id的关键字段。

db.travel.find({},{"passengerId":1,"_id":0}).pretty();

The above query will have the following response:

上述查询将有如下响应。

{ "passengerId" : 145 }
{ "passengerId" : 148 }
{ "passengerId" : 154 }
{ "passengerId" : 168 }

Here, in this query, we excluded the _id field from the response projection. Let’s see the Java driver code for the above query:

在这里,在这个查询中,我们将_id字段从响应投影中排除。让我们看看上述查询的Java驱动代码。

MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("baeldung");
DBCollection collection = database.getCollection("travel");
BasicDBObject queryFilter = new BasicDBObject();
BasicDBObject projection = new BasicDBObject();
projection.put("passengerId", 1);
projection.put("_id", 0);
DBCursor dbCursor = collection.find(queryFilter, projection);
while (dbCursor.hasNext()) {
    System.out.println(dbCursor.next());
}

In the above code, first, we created a MongoClient connection with the local mongo server running on port 27017. Next, we used the find method, which has two parameters, the queryFilter, and projection. The query DBObject contains the filters on which we need to fetch the data. Here we printed all the projected fields of travel documents using the DBCursor.

在上面的代码中,首先,我们创建了一个MongoClient连接,与运行在27017端口的本地mongo服务器相连。接下来,我们使用了find方法,该方法有两个参数,queryFilter,和projection。查询DBObject包含我们需要获取数据的过滤器。在这里,我们使用DBCursor打印了旅行文件的所有投影字段。

4. Using the aggregation Method

4.使用聚合

The aggregation operations in MongoDB process data records and documents and return computed results. It collects values from various documents and groups them together before performing different types of operations on the grouped data, such as sum, average, minimum, maximum, etc.

MongoDB中的aggregation操作处理数据记录和文档并返回计算结果。它从不同的文档中收集数值并将它们分组,然后对分组后的数据进行不同类型的操作,如总和、平均、最小、最大等。

We can use the MongoDB aggregation pipeline when we need to do more complex aggregation. Aggregation pipelines are collections of stages combined with MongoDB query syntax to yield aggregated results.

当我们需要进行更复杂的聚合时,我们可以使用MongoDB的聚合管线。聚合管道是与MongoDB查询语法相结合的阶段集合,以产生聚合的结果。

Let’s look into the aggregation query to retrieve the value by key name:

让我们来看看聚合查询,按键名检索值。

db.travel.aggregate([
{
    "$project":{
        "passengerId":1
    }
}
]).pretty();

The response to the above aggregation query will be:

对上述汇总查询的响应将是。

{ "_id" : ObjectId("623d7f079d55d4e137e47825"), "passengerId" : 145 }
{ "_id" : ObjectId("623d7f079d55d4e137e47826"), "passengerId" : 148 }
{ "_id" : ObjectId("623d7f079d55d4e137e47827"), "passengerId" : 154 }
{ "_id" : ObjectId("623d7f079d55d4e137e47828"), "passengerId" : 168 }

In this case, we used the $project stage of the aggregation pipeline. $project specifies what fields to include or exclude. In our query, we only passed the passengerId into the projection stage.

在这种情况下,我们使用聚合管道的$project阶段。$project指定了要包括或排除哪些字段。在我们的查询中,我们只把passengerId传给了projection阶段。

Let’s look at the Java driver code for the above query:

让我们看一下上述查询的Java驱动代码。

ArrayList<Document> response = new ArrayList<>();
ArrayList<Document> pipeline = new ArrayList<>(Arrays.asList(new Document("$project", new Document("passengerId", 1L))));
database = mongoClient.getDatabase("baeldung");
database.getCollection("travel").aggregate(pipeline).allowDiskUse(true).into(response);
System.out.println("response:- " + response);

We can also write the aggregation pipeline in the following way:

我们也可以用下面的方式来写聚合管道。

ArrayList<Document> response = new ArrayList<>();
ArrayList<Bson> pipeline = new ArrayList<>(Arrays.asList(
  project(fields(Projections.exclude("_id"), Projections.include("passengerId")))));
MongoDatabase database = mongoClient.getDatabase("baeldung");
database.getCollection("travel").aggregate(pipeline).allowDiskUse(true).into(response);
System.out.println("response:- "+response);

We created an aggregation pipeline with the java driver code and set the project stage only to include the passengerId field. Finally, we passed the aggregation pipeline to the aggregate method to retrieve the data.

我们用java驱动代码创建了一个聚合管道,并设置项目阶段只包括passengerId字段。最后,我们将聚合管道传递给aggregate方法来检索数据。

5. Conclusion

5.总结

In this article, we learned to retrieve the value by key name in MongoDB. We explored different methods of MongoDB to fetch the data. First, we retrieve the data using the find method and then the aggregate method. We looked into the use cases of the projection of fields in MongoDB. In short, we implemented the projection of fields using Mongo shell query and Java driver code.

在这篇文章中,我们学习了在MongoDB中按键名检索值。我们探索了MongoDB的不同方法来获取数据。首先,我们使用find方法检索数据,然后使用aggregate方法。我们研究了MongoDB中字段投射的使用情况。简而言之,我们使用Mongo shell查询和Java驱动代码实现了字段的投影。

We can find the implementation of all the cases over on GitHub.

我们可以在GitHub上找到所有案例的实现over