使用查询从 MongoDB 读取数据
概述
在上一个指南中,在 MongoDB 中读取数据,您从没有任何条件匹配的sample_guides.planets
集合中检索了所有文档。
在本指南中,您将查询集合并检索与特定 相等 条件匹配的文档,即指定字段或字段的值必须匹配。
所需时间15分钟
所需条件
到您的 MongoDB 部署的 连接字符串。
已加载到您的集群中的示例数据集 。
已安装的 MongoDB 驱动程序。
步骤
连接到您的MongoDB实例。
提示
在此代码块中有一个注释,用于将连接URI替换为您自己的。将URI字符串替换为您的Atlas连接字符串。
提示
以下是最小必要代码,用于连接到MongoDB。您将在接下来的几个步骤中添加读取数据的代码。
在第5行,将URI字符串替换为您的Atlas连接字符串。
1 using MongoDB.Bson;
2 using MongoDB.Driver;
3
4 // Replace the uri string with your MongoDB deployment's connection string.
5 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7 var 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字符串替换为您的Atlas连接字符串。
1 package main 2 3 import ( 4 "context" 5 6 "go.mongodb.org/mongo-driver/mongo" 7 "go.mongodb.org/mongo-driver/mongo/options" 8 ) 9 10 func 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字符串替换为您的Atlas连接字符串。
1 import com.mongodb.client.*; 2 import com.mongodb.client.model.Filters.*; 3 import org.bson.Document; 4 import org.bson.conversions.Bson; 5 6 public 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连接字符串。
1 const { MongoClient } = require("mongodb"); 2 // Replace the uri string with your MongoDB deployment's connection string. 3 const uri = 4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 5 const client = new MongoClient(uri); 6 async 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 } 17 run().catch(console.dir);
提示
以下是最小必要代码,用于连接到MongoDB。您将在接下来的几个步骤中添加读取数据的代码。
在第4行,将URI字符串替换为您的Atlas连接字符串。
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = 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. 13 client.close()
提示
mongodb+srv
请确保您已使用srv
选项安装了PyMongo。
python3 -m pip install "pymongo[srv]"
获取数据库和集合。
切换到您要查询的数据库和集合。在本例中,您将使用 sample_guides
数据库和 planets
集合。
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<BsonDocument>("planets");
1 // database and colletion code goes here 2 db := client.Database("sample_guides") 3 coll := db.Collection("planets")
1 // database and collection code goes here 2 MongoDatabase db = mongoClient.getDatabase("sample_guides"); 3 MongoCollection<Document> coll = db.getCollection("planets");
// database and collection code goes here const db = client.db("sample_guides"); const coll = db.collection("planets");
# database and collection code goes here db = client.sample_guides coll = db.planets
从 planets
集合中检索特定的文档。
您可以通过应用查询过滤器来从集合中检索特定文档。查询过滤器是一个包含您搜索条件的文档。以下示例演示了如何使用查询过滤器从具有 hasRings
字段且值为 true
的 planets
集合中检索文档。
// find code goes here
var cursor = from planet in coll.AsQueryable()
where planet["hasRings"] == true
select planet;
提示
在将文档发送到 MongoDB 时应使用 BSON.D
,因为 BSON.D
是有序的。这在更复杂的操作中很重要。
1 // find code goes here 2 filter := bson.D{{"hasRings", true}} 3 cursor, err := coll.Find(context.TODO(), filter) 4 if err != nil { 5 panic(err) 6 }
MongoDB Java 驱动程序包括构建器,这些构建器简化了创建查询(和其他操作)的过程。在此,您使用 Filters.eq
构建器来构造查询文档。
1 // find code goes here 2 Bson filter = eq("hasRings", true); 3 MongoCursor<Document> cursor = coll.find(filter).iterator();
// find code goes here const cursor = coll.find({ hasRings: true });
# find code goes here cursor = coll.find({"hasRings": True})
遍历结果。
// iterate code goes here
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document);
}
1 // iterate code goes here 2 for 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 } 9 if err := cursor.Err(); err != nil { 10 panic(err) 11 }
1 // iterate code goes here 2 try { 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和回调指南。
// iterate code goes here await cursor.forEach(console.log);
# iterate code goes here for doc in cursor: print(doc)
检查您的结果。
以下是完整的代码和示例输出。
注意
您的ObjectId
值将与显示的不同。
以下是完整的代码和示例输出。
1 using MongoDB.Bson;
2 using MongoDB.Driver;
3
4 // Replace the uri string with your MongoDB deployment's connection string.
5 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7 var client = new MongoClient(uri);
8
9 // database and collection code goes here
10 var db = client.GetDatabase("sample_guides");
11 var coll = db.GetCollection<BsonDocument>("planets");
12 // find code goes here
13 var cursor = from planet in coll.AsQueryable()
14 where planet["hasRings"] == true
15 select planet;
16 // iterate code goes here
17 foreach (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, ... }
以下是完整的代码和示例输出。为了显示目的,已截断输出文档。
1 package main 2 3 import ( 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 12 func 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 ... ]]
以下是完整的代码和示例输出。
1 import com.mongodb.client.*; 2 import com.mongodb.client.model.Filters.*; 3 import org.bson.Document; 4 import org.bson.conversions.Bson; 5 6 public 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, ... }
以下是完整的代码和示例输出。
1 const { MongoClient } = require("mongodb"); 2 // Replace the uri string with your MongoDB deployment's connection string. 3 const uri = 4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 5 const client = new MongoClient(uri); 6 async 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 } 23 run().catch(console.dir);
{... 'name': 'Uranus', 'hasRings': True, ...} {... 'name': 'Neptune', 'hasRings': True, ... } {... 'name': 'Jupiter', 'hasRings': True, ... } {... 'name': 'Saturn', 'hasRings': True, ... }
以下是完整的代码和示例输出。
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = MongoClient(uri) 7 8 # database and collection code goes here 9 db = client.sample_guides 10 coll = db.planets 11 # find code goes here 12 cursor = coll.find({"hasRings": True}) 13 # iterate code goes here 14 for doc in cursor: 15 print(doc) 16 17 # Close the connection to MongoDB when you're done. 18 client.close()
{... 'name': 'Uranus', 'hasRings': True, ...} {... 'name': 'Neptune', 'hasRings': True, ... } {... 'name': 'Jupiter', 'hasRings': True, ... } {... 'name': 'Saturn', 'hasRings': True, ... }
使用多个条件进行查询。
您也可以使用多个条件查询集合。以下示例说明如何使用多个条件从具有hasRings
字段值为false
和Argon(Ar)
作为mainAtmosphere
字段条目的planets
集合中检索文档。
以下是完整的代码和示例输出。
1 // find code goes here
2 var 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"], ... }
以下是完整的代码和示例输出。为了显示目的,已截断输出文档。
1 // find code goes here 2 filter := bson.D{ 3 {"$and", 4 bson.A{ 5 bson.D{{"hasRings", false}}, 6 bson.D{{"mainAtmosphere", "Ar"}}, 7 }, 8 }, 9 } 10 cursor, err := coll.Find(context.TODO(), filter) 11 if err != nil { 12 panic(err) 13 }
map[... hasRings:false mainAtmosphere:[CO2 Ar N] ... ]] map[... hasRings:false mainAtmosphere:[N O2 Ar] ... ]]
以下是完整的代码和示例输出。
1 // find code goes here 2 Bson filter = and(eq("hasRings", false), eq("mainAtmosphere", "Ar")); 3 MongoCursor<Document> cursor = coll.find(filter).iterator();
{..., "name" : "Mars", "mainAtmosphere" : ["CO2", "Ar", "N"], ... } {..., "name" : "Earth", "mainAtmosphere" : ["N", "O2", "Ar"], ... }
以下是完整的代码和示例输出。
1 // find code goes here 2 const cursor = coll.find({ hasRings: false, mainAtmosphere: "Ar" });
{..., "name" : "Mars", "mainAtmosphere" : ["CO2", "Ar", "N"], ... } {..., "name" : "Earth", "mainAtmosphere" : ["N", "O2", "Ar"], ... }
1 # find code goes here 2 cursor = coll.find({"hasRings": False, "mainAtmosphere": "Ar"})
{..., "name" : "Mars", "mainAtmosphere" : ["CO2", "Ar", "N"], ... } {..., "name" : "Earth", "mainAtmosphere" : ["N", "O2", "Ar"], ... }
尽管mainAtmosphere
字段是一个数组,但您可以使用严格的相等查询,因为MongoDB将数组视为一等类型。在查询执行期间,MongoDB将数组中的每个条目与您指定的值(在本例中为"Ar"
)进行比较,以确定文档是否满足您的条件。
摘要
如果您已完成本指南,您已使用特定的相等条件从MongoDB中检索数据。当您确切知道您要搜索什么时,这很有用,例如商品编号、用户名或化学元素。
在下一指南中,您将学习如何使用比较运算符从MongoDB中读取数据,以检索符合更广泛条件的文档。
另请参阅
查看以下资源以获取有关此处介绍的概念的更深入信息
《MongoDB C# 驱动 文档
《MongoDB Go 驱动 文档
《MongoDB Java(Sync) 驱动 文档
《MongoDB Node.js 驱动 文档
《PyMongo 文档