使用运算符和组合查询读取数据
概述
在前面的读取指南中,使用查询从MongoDB中读取数据,您使用了等式查询读取数据。在本指南中,您将
从
sample_guides.planets
集合中读取数据,使用 MongoDB 的比较运算符。组合查询条件以创建复合查询。
使用 点表示法 查询嵌套字段。
所需时间20分钟
所需物品
到您的 MongoDB 部署的 连接字符串。
已加载到您的集群中的 示例数据集。
已安装的 MongoDB 驱动程序。
程序
使用嵌套字段和比较运算符读取数据
在本练习中,您将使用比较运算符读取数据。
连接到您的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字符串替换为您自己的Atlas连接字符串。
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字符串替换为您自己的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 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。