使用操作符和复合查询读取数据
Overview
在上一篇阅读指南使用查询从MongoDB中读取数据中,您使用相等查询来读取数据。 在本指南中,您将:
使用 MongoDB 的比较操作符从
sample_guides.planets
集合中读取数据。组合查询条件以进行复合查询。
使用点符号来查询嵌入字段。
所需时间:20 分钟
您需要的工具
步骤
使用嵌入字段和比较操作符读取数据
本练习中,您将使用比较操作符读取数据。
连接到您的 MongoDB 实例。
提示
下面概述了连接到 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 var coll = client.GetDatabase("sample_guides").GetCollection<BsonDocument>("planets");
10 // find code goes here
11 var cursor = coll.AsQueryable();
12
13 foreach (var document in cursor)
14 {
15 Console.WriteLine(document);
16 }
提示
下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来读取数据。
在第 13 行,将 URI string替换为您自己的Atlas连接string 。
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 coll := client.Database("sample_guides").Collection("planets") 26 27 // find code goes here 28 filter := bson.D{{}} 29 cursor, err := coll.Find(context.TODO(), filter) 30 if err != nil { 31 panic(err) 32 } 33 34 for cursor.Next(context.TODO()) { 35 var result bson.M 36 if err := cursor.Decode(&result); err != nil { 37 panic(err) 38 } 39 fmt.Println(result) 40 } 41 if err := cursor.Err(); err != nil { 42 panic(err) 43 } 44 }
提示
下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来读取数据。
在第 8 行,将 URI string替换为您自己的Atlas连接string 。
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 MongoCollection<Document> coll = mongoClient.getDatabase("sample_guides") 12 .getCollection("planets"); 13 // find code goes here 14 Bson filter = Filters.empty(); 15 MongoCursor<Document> cursor = coll.find(filter).iterator(); 16 try { 17 while (cursor.hasNext()) { 18 System.out.println(cursor.next().toJson()); 19 } 20 } finally { 21 cursor.close(); 22 } 23 } 24 } 25 }
提示
下面概述了连接到 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 const coll = client.db("sample_guides").collection("planets"); 10 11 // find code goes here 12 let cursor = coll.find(); 13 14 await cursor.forEach(console.log); 15 } finally { 16 // Ensures that the client will close when you finish/error 17 await client.close(); 18 } 19 } 20 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 coll = client.sample_guides.planets 8 9 # find code goes here 10 cursor = coll.find() 11 12 for doc in cursor: 13 print(doc) 14 15 # Close the connection to MongoDB when you're done. 16 client.close()
提示
mongodb+srv
确保您已安装带 srv
选项的 PyMongo。
python3 -m pip install "pymongo[srv]"
使用小于操作符选择文档。
在此查询中使用点表示法来选择嵌入式文档surfaceTemperatureC
中mean
字段的值小于15度(摄氏度)的文档。
// find code goes here
var cursor = from planet in coll.AsQueryable()
where planet["surfaceTemperatureC.mean"] < 15
select planet;
1 // find code goes here 2 filter := bson.D{{"surfaceTemperatureC.mean", bson.D{{"$lt", 15}}}} 3 cursor, err := coll.Find(context.TODO(), filter) 4 if err != nil { 5 panic(err) 6 }
MongoDB Java驱动程序包含可简化创建查询(和其他操作)进程的构建器。 在这里,您使用Filters.lt
构建器来构造查询文档。
1 // find code goes here 2 Bson filter = lt("surfaceTemperatureC.mean", 15); 3 MongoCursor<Document> cursor = coll.find(filter).iterator();
// find code goes here const cursor = coll.find({ "surfaceTemperatureC.mean": { $lt: 15 } });
# find code goes here cursor = coll.find({"surfaceTemperatureC.mean": {"$lt": 15}})
检查你的结果。
以下是完整代码,然后是样本输出。我们截断了结果以便于显示。
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 var coll = client.GetDatabase("sample_guides").GetCollection<BsonDocument>("planets");
10 // find code goes here
11 var cursor = from planet in coll.AsQueryable()
12 where planet["surfaceTemperatureC.mean"] < 15
13 select planet;
14
15 foreach (var document in cursor)
16 {
17 Console.WriteLine(document);
18 }
{ "name" : "Uranus", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -197.19999999999999 }, ... } { "name" : "Mars", "surfaceTemperatureC" : { "min" : -143, "max" : 35, "mean" : -63 }, ... } { "name" : "Neptune", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -201 }, ... } { "name" : "Jupiter", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -145.15000000000001 }, ... } { "name" : "Earth", "surfaceTemperatureC" : { "min" : -89.200000000000003, "max" : 56.700000000000003, "mean" : 14 }, ... } { "name" : "Saturn", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -139.15000000000001 }, ... }
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 coll := client.Database("sample_guides").Collection("planets") 26 27 // find code goes here 28 filter := bson.D{{"surfaceTemperatureC.mean", bson.D{{"$lt", 15}}}} 29 cursor, err := coll.Find(context.TODO(), filter) 30 if err != nil { 31 panic(err) 32 } 33 34 for cursor.Next(context.TODO()) { 35 var result bson.M 36 if err := cursor.Decode(&result); err != nil { 37 panic(err) 38 } 39 fmt.Println(result) 40 } 41 if err := cursor.Err(); err != nil { 42 panic(err) 43 } 44 }
map[ name:Uranus surfaceTemperatureC:map[max:<nil> mean:-197.2 min:<nil>] ...] map[ name:Mars surfaceTemperatureC:map[max:35 mean:-63 min:-143] ... ] map[ name:Neptune surfaceTemperatureC:map[max:<nil> mean:-201 min:<nil>] ... ] map[ name:Jupiter surfaceTemperatureC:map[max:<nil> mean:-145.15 min:<nil>] ... ] map[ name:Earth surfaceTemperatureC:map[max:56.7 mean:14 min:-89.2]] map[ name:Saturn surfaceTemperatureC:map[max:<nil> mean:-139.15 min:<nil>] ... ]
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 MongoCollection<Document> coll = mongoClient.getDatabase("sample_guides") 12 .getCollection("planets"); 13 14 // find code goes here 15 Bson filter = lt("surfaceTemperatureC.mean", 15); 16 MongoCursor<Document> cursor = coll.find(filter).iterator(); 17 18 // iterate code goes here 19 try { 20 while (cursor.hasNext()) { 21 System.out.println(cursor.next().toJson()); 22 } 23 } finally { 24 cursor.close(); 25 } 26 } 27 } 28 }
{ "name" : "Uranus", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -197.19999999999999 }, ... } { "name" : "Mars", "surfaceTemperatureC" : { "min" : -143, "max" : 35, "mean" : -63 }, ... } { "name" : "Neptune", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -201 }, ... } { "name" : "Jupiter", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -145.15000000000001 }, ... } { "name" : "Earth", "surfaceTemperatureC" : { "min" : -89.200000000000003, "max" : 56.700000000000003, "mean" : 14 }, ... } { "name" : "Saturn", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -139.15000000000001 }, ... }
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 const coll = client.db("sample_guides").collection("planets"); 10 11 // find code goes here 12 const cursor = coll.find({ "surfaceTemperatureC.mean": { $lt: 15 } }); 13 14 await cursor.forEach(console.log); 15 } finally { 16 // Ensures that the client will close when you finish/error 17 await client.close(); 18 } 19 } 20 run().catch(console.dir);
{ "name" : "Uranus", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -197.19999999999999 }, ... } { "name" : "Mars", "surfaceTemperatureC" : { "min" : -143, "max" : 35, "mean" : -63 }, ... } { "name" : "Neptune", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -201 }, ... } { "name" : "Jupiter", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -145.15000000000001 }, ... } { "name" : "Earth", "surfaceTemperatureC" : { "min" : -89.200000000000003, "max" : 56.700000000000003, "mean" : 14 }, ... } { "name" : "Saturn", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -139.15000000000001 }, ... }
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 coll = client.sample_guides.planets 8 9 # find code goes here 10 cursor = coll.find({"surfaceTemperatureC.mean": {"$lt": 15}}) 11 12 for doc in cursor: 13 print(doc) 14 15 # Close the connection to MongoDB when you're done. 16 client.close()
{ "name" : "Uranus", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -197.19999999999999 }, ... } { "name" : "Mars", "surfaceTemperatureC" : { "min" : -143, "max" : 35, "mean" : -63 }, ... } { "name" : "Neptune", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -201 }, ... } { "name" : "Jupiter", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -145.15000000000001 }, ... } { "name" : "Earth", "surfaceTemperatureC" : { "min" : -89.200000000000003, "max" : 56.700000000000003, "mean" : 14 }, ... } { "name" : "Saturn", "surfaceTemperatureC" : { "min" : null, "max" : null, "mean" : -139.15000000000001 }, ... }
使用复合查询读取数据
现在您将使用 AND 和 OR 逻辑从 MongoDB 读取数据,形成复合查询。
写入 AND 查询。
要在 MongoDB 中编写匹配所有查询谓词(即逻辑 AND)的复合查询,请指定您希望在查找文档中匹配的所有字段。默认情况下,MongoDB 会匹配所有字段。 如果您按照上一份指南进行了操作,您已经完成了这项工作!
以下示例检索 planets
集合中 surfaceTemperatureC.mean
字段小于 15
且 surfaceTemperatureC.min
字段大于 -100
的所有文档。
1 // find code goes here
2 var cursor = from planet in coll.AsQueryable()
3 where planet["surfaceTemperatureC.mean"] < 15 && planet["surfaceTemperatureC.min"] > -100
4 select planet;
5
{'name': 'Earth', 'orderFromSun': 3, ...}
1 // find code goes here 2 filter := bson.D{ 3 {"$and", 4 bson.A{ 5 bson.D{{"surfaceTemperatureC.mean", 6 bson.D{{"$lt", 15}}, 7 }}, 8 bson.D{{"surfaceTemperatureC.min", 9 bson.D{{"$gt", -100}}, 10 }}, 11 }, 12 }, 13 } 14 cursor, err := coll.Find(context.TODO(), filter) 15 if err != nil { 16 panic(err) 17 }
map[name:Earth orderFromSun:3 ...]
1 // find code goes here 2 Bson filter = and(lt("surfaceTemperatureC.mean", 15), gt("surfaceTemperatureC.min", -100)); 3 MongoCursor<Document> cursor = coll.find(filter).iterator();
{'name': 'Earth', 'orderFromSun': 3, ...}
1 // find code goes here 2 const cursor = coll.find({ 3 "surfaceTemperatureC.mean": { $lt: 15 }, 4 "surfaceTemperatureC.min": { $gt: -100 }, 5 });
{'name': 'Earth', 'orderFromSun': 3, ...}
注意
隐式 AND
指定多个条件很常见。如果不指定任何查询运算符,驱动程序将以 AND 方式解释您的条件。但是,有时在指定多个条件时必须明确,特别是在同一字段上指定条件时。
例如,要查找 planets
集合中 orderFromSun
值大于 2
且小于 5
的文档,您必须使用 $and
查询运算符。
1 const cursor = coll.find({ 2 $and: [{ orderFromSun: { $gt: 2 } }, { orderFromSun: { $lt: 5 } }], 3 });
{'name': 'Mars', 'orderFromSun': 4, ... } {'name': 'Earth', 'orderFromSun': 3, ... }
1 cursor = coll.find( 2 {"$and": [{"orderFromSun": {"$gt": 2}}, {"orderFromSun": {"$lt": 5}}]} 3 )
{'name': 'Mars', 'orderFromSun': 4, ... } {'name': 'Earth', 'orderFromSun': 3, ... }
如果不使用 $and
操作符,驱动程序将在查询筛选器中多次遇到相同的键,并使用遇到的最后一个键。 尝试省略 $and
操作符,看看会发生什么。
1 # find code goes here 2 cursor = coll.find( 3 {"surfaceTemperatureC.mean": {"$lt": 15}, "surfaceTemperatureC.min": {"$gt": -100}} 4 )
{'name': 'Earth', 'orderFromSun': 3, ...}
注意
隐式 AND
指定多个条件很常见。如果不指定任何查询运算符,驱动程序将以 AND 方式解释您的条件。但是,有时在指定多个条件时必须明确,特别是在同一字段上指定条件时。
例如,要查找 planets
集合中 orderFromSun
值大于 2
且小于 5
的文档,您必须使用 $and
查询运算符。
1 const cursor = coll.find({ 2 $and: [{ orderFromSun: { $gt: 2 } }, { orderFromSun: { $lt: 5 } }], 3 });
{'name': 'Mars', 'orderFromSun': 4, ... } {'name': 'Earth', 'orderFromSun': 3, ... }
1 cursor = coll.find( 2 {"$and": [{"orderFromSun": {"$gt": 2}}, {"orderFromSun": {"$lt": 5}}]} 3 )
{'name': 'Mars', 'orderFromSun': 4, ... } {'name': 'Earth', 'orderFromSun': 3, ... }
如果不使用 $and
操作符,驱动程序将在查询筛选器中多次遇到相同的键,并使用遇到的最后一个键。 尝试省略 $and
操作符,看看会发生什么。
编写 OR 查询。
如果您要指定互斥的条件,则需要使用 OR 查询。例如,您无法匹配 planets
集合中 orderFromSun
值大于 7
且小于 2
的文档。
以下示例展示了如何使用 $or
操作符来表达互斥条件。
1 // find code goes here
2 var cursor = from planet in coll.AsQueryable()
3 where planet["orderFromSun"] > 7 || planet["orderFromSun"] < 2
4 select planet;
{ name: 'Mercury', orderFromSun: 1, ... } { name: 'Neptune', orderFromSun: 8, ... }
1 // find code goes here 2 filter := bson.D{ 3 {"$or", 4 bson.A{ 5 bson.D{{"orderFromSun", 6 bson.D{{"$gt", 7}}, 7 }}, 8 bson.D{{"orderFromSun", bson.D{{"$lt", 2}}}}, 9 }, 10 }, 11 } 12 13 cursor, err := coll.Find(context.TODO(), filter) 14 if err != nil { 15 panic(err) 16 }
map[name:Mercury orderFromSun:1 ...] map[name:Neptune orderFromSun:8 ...]
1 // find code goes here 2 Bson filter = or(gt("orderFromSun", 7), lt("orderFromSun", 2)); 3 MongoCursor<Document> cursor = coll.find(filter).iterator();
{ name: 'Mercury', orderFromSun: 1, ... } { name: 'Neptune', orderFromSun: 8, ... }
1 // find code goes here 2 const cursor = coll.find({ 3 $or: [{ orderFromSun: { $gt: 7 } }, { orderFromSun: { $lt: 2 } }], 4 });
{ name: 'Mercury', orderFromSun: 1, ... } { name: 'Neptune', orderFromSun: 8, ... }
1 # find code goes here 2 cursor = coll.find( 3 { 4 "$or": [ 5 {"orderFromSun": {"$gt": 7}}, 6 {"orderFromSun": {"$lt": 2}}, 7 ] 8 } 9 )
{ name: 'Mercury', orderFromSun: 1, ... } { name: 'Neptune', orderFromSun: 8, ... }
总结
如果您已成功完成本指南,那么您已经使用 MongoDB 查询操作符和复合查询从 MongoDB 读取了数据。
您几乎可以使用无限的方式组合查询运算符以表示复杂查询。例如,您可以查询具有环形结构并在大气中含有特定化合物的文档,或者具有特定温度并且名称中均包含“E”字母的文档。
在下一个指南中,您将学习如何将数据插入 MongoDB。