Docs 菜单
Docs 主页
/
入门指南

通过查询从 MongoDB 中读取数据

在上一篇指南在MongoDB中读取数据 中,您从 sample_guides.planets集合中检索了所有文档,但未指定文档应满足的任何条件。

在本指南中,您将查询集合并检索与特定相等条件匹配的文档,这意味着指定字段的值必须匹配。

所需时间:15 分钟

1

提示

在此代码块中有一条注释,用于将连接 URI 替换为您自己的 URI。用您自己的 Atlas 连接字符串替换 URI 字符串。

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来读取数据。

在第 5 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

CrudRead.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the uri string with your MongoDB deployment's connection string.
5var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7var client = new MongoClient(uri);
8
9// database and collection code goes here
10// find code goes here
11// iterate code goes here
12
13
14

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来读取数据。

在第 11 行,将 URI string替换为您自己的Atlas连接string 。

crudRead.go
1package main
2
3import (
4 "context"
5
6 "go.mongodb.org/mongo-driver/mongo"
7 "go.mongodb.org/mongo-driver/mongo/options"
8)
9
10func main() {
11 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
12
13 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
14 if err != nil {
15 panic(err)
16 }
17
18 defer func() {
19 if err = client.Disconnect(context.TODO()); err != nil {
20 panic(err)
21 }
22 }()
23
24 // database and colletion code goes here
25 // find code goes here
26 // iterate code goes here
27}

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来读取数据。

在第 8 行,将 URI string替换为您自己的Atlas连接string 。

CrudRead.java
1import com.mongodb.client.*;
2import com.mongodb.client.model.Filters.*;
3import org.bson.Document;
4import org.bson.conversions.Bson;
5
6public class CrudRead {
7 public static void main(String[] args) {
8 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
9
10 try (MongoClient mongoClient = MongoClients.create(uri)) {
11 // database and collection code goes here
12 // find code goes here
13 // iterate code goes here
14 }
15 }
16}

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来读取数据。

在第 4 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

crud-read.js
1const { MongoClient } = require("mongodb");
2// Replace the uri string with your MongoDB deployment's connection string.
3const uri =
4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
5const client = new MongoClient(uri);
6async function run() {
7 try {
8 await client.connect();
9 // database and collection code goes here
10 // find code goes here
11 // iterate code goes here
12 } finally {
13 // Ensures that the client will close when you finish/error
14 await client.close();
15 }
16}
17run().catch(console.dir);

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来读取数据。

在第 4 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

crud_read.py
1from pymongo import MongoClient
2
3# Replace the uri string with your MongoDB deployment's connection string.
4uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
5
6client = MongoClient(uri)
7
8# database and collection code goes here
9# find code goes here
10# iterate code goes here
11
12# Close the connection to MongoDB when you're done.
13client.close()

提示

mongodb+srv

确保您已安装带 srv 选项的 PyMongo。

python3 -m pip install "pymongo[srv]"
2

切换到要查询的数据库和集合。在本例中,您将使用 sample_guides 数据库和 planets 集合。

CrudRead.cs
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<BsonDocument>("planets");
crudRead.go
1// database and colletion code goes here
2db := client.Database("sample_guides")
3coll := db.Collection("planets")
CrudRead.java
1// database and collection code goes here
2MongoDatabase db = mongoClient.getDatabase("sample_guides");
3MongoCollection<Document> coll = db.getCollection("planets");
crud-read.js
// database and collection code goes here
const db = client.db("sample_guides");
const coll = db.collection("planets");
crud_read.py
# database and collection code goes here
db = client.sample_guides
coll = db.planets
3

您可通过应用查询筛选器从集合中检索特定文档。查询筛选器是指包含所搜索条件的文档。以下示例说明如何了如何使用查询筛选器从 planets 集合检索包含值为 truehasRings 字段的文档。

CrudRead.cs
// find code goes here
var cursor = from planet in coll.AsQueryable()
where planet["hasRings"] == true
select planet;

提示

BSON.D 在向MongoDB发送文档时应使用 BSON.D,因为是有序的。 这对于更复杂的操作非常重要。

crudRead.go
1// find code goes here
2filter := bson.D{{"hasRings", true}}
3cursor, err := coll.Find(context.TODO(), filter)
4if err != nil {
5 panic(err)
6}

MongoDB Java驱动程序包括构建器,可简化创建查询(和其他操作)的进程。 在这里,您使用Filters.eq构建器来构造查询文档。

CrudRead.java
1// find code goes here
2Bson filter = eq("hasRings", true);
3MongoCursor<Document> cursor = coll.find(filter).iterator();
crud-read.js
// find code goes here
const cursor = coll.find({ hasRings: true });
crud_read.py
# find code goes here
cursor = coll.find({"hasRings": True})
4
CrudRead.cs
// iterate code goes here
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document);
}
crudRead.go
1// iterate code goes here
2for cursor.Next(context.TODO()) {
3 var result bson.M
4 if err := cursor.Decode(&result); err != nil {
5 panic(err)
6 }
7 fmt.Println(result)
8}
9if err := cursor.Err(); err != nil {
10 panic(err)
11}
CrudRead.java
1// iterate code goes here
2try {
3 while (cursor.hasNext()) {
4 System.out.println(cursor.next().toJson());
5 }
6} finally {
7 cursor.close();
8}

迭代结果并将其打印到控制台。默认情况下,此类操作在 MongoDB Node.js 驱动程序中是异步的,这意味着 Node.js 运行时在等待这些操作完成执行的过程中,不会阻塞其他操作。

为了简化操作,您可以指定 await 关键字,这导致运行时等待操作。这通常要比指定 回调 或链式调用 Promise 更加简便。

有关更多信息,请参阅Promise 和回调指南。

crud-read.js
// iterate code goes here
await cursor.forEach(console.log);
crud_read.py
# iterate code goes here
for doc in cursor:
print(doc)
5

以下是完整的代码,然后是样本输出。

注意

您的 ObjectId 值将与显示的值不同。

以下是完整的代码,然后是样本输出。

CrudRead.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the uri string with your MongoDB deployment's connection string.
5var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7var client = new MongoClient(uri);
8
9// database and collection code goes here
10var db = client.GetDatabase("sample_guides");
11var coll = db.GetCollection<BsonDocument>("planets");
12// find code goes here
13var cursor = from planet in coll.AsQueryable()
14 where planet["hasRings"] == true
15 select planet;
16// iterate code goes here
17foreach (var document in cursor)
18{
19 Console.WriteLine(document);
20}
21
22
{... 'name': 'Uranus', 'hasRings': True, ...}
{... 'name': 'Neptune', 'hasRings': True, ... }
{... 'name': 'Jupiter', 'hasRings': True, ... }
{... 'name': 'Saturn', 'hasRings': True, ... }

以下是完整代码,然后是示例输出。为便于显示,此处对输出文件进行了截断。

crudRead.go
1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
14
15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
16 if err != nil {
17 panic(err)
18 }
19
20 defer func() {
21 if err = client.Disconnect(context.TODO()); err != nil {
22 panic(err)
23 }
24 }()
25
26 // database and colletion code goes here
27 db := client.Database("sample_guides")
28 coll := db.Collection("planets")
29
30 // find code goes here
31 filter := bson.D{{"hasRings", true}}
32 cursor, err := coll.Find(context.TODO(), filter)
33 if err != nil {
34 panic(err)
35 }
36
37 // iterate code goes here
38 for cursor.Next(context.TODO()) {
39 var result bson.M
40 if err := cursor.Decode(&result); err != nil {
41 panic(err)
42 }
43 fmt.Println(result)
44 }
45 if err := cursor.Err(); err != nil {
46 panic(err)
47 }
48
49}
map[... hasRings:true name:Uranus ... ]]
map[... hasRings:true name:Neptune ... ]]
map[... hasRings:true name:Jupiter ... ]]
map[... hasRings:true name:Saturn ... ]]

以下是完整的代码,然后是样本输出。

CrudRead.java
1import com.mongodb.client.*;
2import com.mongodb.client.model.Filters.*;
3import org.bson.Document;
4import org.bson.conversions.Bson;
5
6public class CrudRead {
7 public static void main(String[] args) {
8 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
9
10 try (MongoClient mongoClient = MongoClients.create(uri)) {
11 // database and collection code goes here
12 MongoDatabase db = mongoClient.getDatabase("sample_guides");
13 MongoCollection<Document> coll = db.getCollection("planets");
14
15 // find code goes here
16 Bson filter = eq("hasRings", true);
17 MongoCursor<Document> cursor = coll.find(filter).iterator();
18
19 // iterate code goes here
20 try {
21 while (cursor.hasNext()) {
22 System.out.println(cursor.next().toJson());
23 }
24 } finally {
25 cursor.close();
26 }
27 }
28 }
29}
{... 'name': 'Uranus', 'hasRings': True, ...}
{... 'name': 'Neptune', 'hasRings': True, ... }
{... 'name': 'Jupiter', 'hasRings': True, ... }
{... 'name': 'Saturn', 'hasRings': True, ... }

以下是完整的代码,然后是样本输出。

crud-read.js
1const { MongoClient } = require("mongodb");
2// Replace the uri string with your MongoDB deployment's connection string.
3const uri =
4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
5const client = new MongoClient(uri);
6async function run() {
7 try {
8 await client.connect();
9 // database and collection code goes here
10 const db = client.db("sample_guides");
11 const coll = db.collection("planets");
12
13 // find code goes here
14 const cursor = coll.find({ hasRings: true });
15
16 // iterate code goes here
17 await cursor.forEach(console.log);
18 } finally {
19 // Ensures that the client will close when you finish/error
20 await client.close();
21 }
22}
23run().catch(console.dir);
{... 'name': 'Uranus', 'hasRings': True, ...}
{... 'name': 'Neptune', 'hasRings': True, ... }
{... 'name': 'Jupiter', 'hasRings': True, ... }
{... 'name': 'Saturn', 'hasRings': True, ... }

以下是完整的代码,然后是样本输出。

crud_read.py
1from pymongo import MongoClient
2
3# Replace the uri string with your MongoDB deployment's connection string.
4uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
5
6client = MongoClient(uri)
7
8# database and collection code goes here
9db = client.sample_guides
10coll = db.planets
11# find code goes here
12cursor = coll.find({"hasRings": True})
13# iterate code goes here
14for doc in cursor:
15 print(doc)
16
17# Close the connection to MongoDB when you're done.
18client.close()
{... 'name': 'Uranus', 'hasRings': True, ...}
{... 'name': 'Neptune', 'hasRings': True, ... }
{... 'name': 'Jupiter', 'hasRings': True, ... }
{... 'name': 'Saturn', 'hasRings': True, ... }
6

您还可以使用多个条件查询集合。以下示例说明如何使用多个条件从 planets 集合中检索文档,这些文档的 hasRings 字段的值为 false,并且 Argon(Ar) 作为 mainAtmosphere 字段中的条目。

以下是完整的代码,然后是样本输出。

CrudRead.cs
1// find code goes here
2var cursor = from planet in coll.AsQueryable()
3 where planet["hasRings"] == false
4 where planet["mainAtmosphere"] == "Ar"
5 select planet;
{..., "name" : "Mars", "mainAtmosphere" : ["CO2", "Ar", "N"], ... }
{..., "name" : "Earth", "mainAtmosphere" : ["N", "O2", "Ar"], ... }

以下是完整代码,然后是示例输出。为便于显示,此处对输出文件进行了截断。

crudRead.go
1// find code goes here
2filter := bson.D{
3 {"$and",
4 bson.A{
5 bson.D{{"hasRings", false}},
6 bson.D{{"mainAtmosphere", "Ar"}},
7 },
8 },
9}
10cursor, err := coll.Find(context.TODO(), filter)
11if err != nil {
12 panic(err)
13}
map[... hasRings:false mainAtmosphere:[CO2 Ar N] ... ]]
map[... hasRings:false mainAtmosphere:[N O2 Ar] ... ]]

以下是完整的代码,然后是样本输出。

CrudRead.java
1// find code goes here
2Bson filter = and(eq("hasRings", false), eq("mainAtmosphere", "Ar"));
3MongoCursor<Document> cursor = coll.find(filter).iterator();
{..., "name" : "Mars", "mainAtmosphere" : ["CO2", "Ar", "N"], ... }
{..., "name" : "Earth", "mainAtmosphere" : ["N", "O2", "Ar"], ... }

以下是完整的代码,然后是样本输出。

crud-read.js
1// find code goes here
2const cursor = coll.find({ hasRings: false, mainAtmosphere: "Ar" });
{..., "name" : "Mars", "mainAtmosphere" : ["CO2", "Ar", "N"], ... }
{..., "name" : "Earth", "mainAtmosphere" : ["N", "O2", "Ar"], ... }
crud_read.py
1# find code goes here
2cursor = coll.find({"hasRings": False, "mainAtmosphere": "Ar"})
{..., "name" : "Mars", "mainAtmosphere" : ["CO2", "Ar", "N"], ... }
{..., "name" : "Earth", "mainAtmosphere" : ["N", "O2", "Ar"], ... }

即使 mainAtmosphere 字段是一个数组,您也可以使用严格相等查询,因为 MongoDB 将数组视为第一类类型。在执行查询期间,MongoDB 会将数组中的每个条目与您指定的值(在本例中为 "Ar")进行比较,以确定文档是否符合您的标准。

如果您已完成本指南,则您已使用特定的等值条件从 MongoDB 中检索数据。当您确切地知道要搜索的内容(例如商品编号、用户名或化学元素)时,这非常有用。

在下一篇指南中,您将学习如何使用比较运算符从 MongoDB 读取数据,以检索与更广泛的条件相匹配的文档。

如需深入了解此处介绍的概念,请参阅以下资源:

接下来的步骤
使用操作符和复合查询读取数据
20 分钟

使用操作符和复合查询在 MongoDB 中检索文档。

入门指南
第2章
CRUD
  • 添加 MongoDB 驱动程序
  • 从 MongoDB 中读取数据
  • 通过查询从 MongoDB 中读取数据
  • 使用操作符和复合查询读取数据
  • 将数据插入 MongoDB
  • 在 MongoDB 中更新数据
  • 从 MongoDB 中删除数据