文档菜单
文档首页
/
从指南开始

使用运算符和组合查询读取数据

在前面的读取指南中,使用查询从MongoDB中读取数据,您使用了等式查询读取数据。在本指南中,您将

  • sample_guides.planets 集合中读取数据,使用 MongoDB 的比较运算符。

  • 组合查询条件以创建复合查询。

  • 使用 点表示法 查询嵌套字段。

所需时间20分钟

在本练习中,您将使用比较运算符读取数据。

1

提示

以下是最小化代码的概述,用于连接到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
9var coll = client.GetDatabase("sample_guides").GetCollection<BsonDocument>("planets");
10// find code goes here
11var cursor = coll.AsQueryable();
12
13foreach (var document in cursor)
14{
15 Console.WriteLine(document);
16}

提示

以下是最小化代码的概述,用于连接到MongoDB。您将在接下来的几个步骤中添加代码以读取数据。

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

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 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连接字符串。

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 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连接字符串。

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 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}
20run().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)
7coll = client.sample_guides.planets
8
9# find code goes here
10cursor = coll.find()
11
12for doc in cursor:
13 print(doc)
14
15# Close the connection to MongoDB when you're done.
16client.close()

提示

mongodb+srv

确保您已使用srv选项安装了PyMongo。

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

使用在此查询中使用点表示法来选择那些嵌入文档中的surfaceTemperatureC字段的mean字段的值小于15度的文档。

CrudRead.cs
// find code goes here
var cursor = from planet in coll.AsQueryable()
where planet["surfaceTemperatureC.mean"] < 15
select planet;
crudRead.go
1// find code goes here
2filter := bson.D{{"surfaceTemperatureC.mean", bson.D{{"$lt", 15}}}}
3cursor, err := coll.Find(context.TODO(), filter)
4if err != nil {
5 panic(err)
6}

MongoDB Java 驱动程序包括构建器,这些构建器简化了创建查询(以及其他操作)的过程。在这里,您使用 Filters.lt 构建器来构造查询文档。

CrudRead.java
1// find code goes here
2Bson filter = lt("surfaceTemperatureC.mean", 15);
3MongoCursor<Document> cursor = coll.find(filter).iterator();
crud-read.js
// find code goes here
const cursor = coll.find({ "surfaceTemperatureC.mean": { $lt: 15 } });
crud_read.py
# find code goes here
cursor = coll.find({"surfaceTemperatureC.mean": {"$lt": 15}})
3

以下是完整代码及示例输出。结果已截断以供显示。

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
9var coll = client.GetDatabase("sample_guides").GetCollection<BsonDocument>("planets");
10// find code goes here
11var cursor = from planet in coll.AsQueryable()
12 where planet["surfaceTemperatureC.mean"] < 15
13 select planet;
14
15foreach (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 }, ... }
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 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>] ... ]
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 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 }, ... }
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 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}
20run().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 }, ... }
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)
7coll = client.sample_guides.planets
8
9# find code goes here
10cursor = coll.find({"surfaceTemperatureC.mean": {"$lt": 15}})
11
12for doc in cursor:
13 print(doc)
14
15# Close the connection to MongoDB when you're done.
16client.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 读取数据以形成复合查询。

1

要编写 MongoDB 中的复合查询(即逻辑 AND),指定您希望匹配的所有字段。默认情况下,MongoDB 匹配所有字段。如果您遵循了之前的指南,您已经这样做过了!

以下示例检索了planets集合中所有surfaceTemperatureC.mean字段值小于15并且surfaceTemperatureC.min字段值大于-100的文档。

CrudRead.cs
1// find code goes here
2var cursor = from planet in coll.AsQueryable()
3 where planet["surfaceTemperatureC.mean"] < 15 && planet["surfaceTemperatureC.min"] > -100
4 select planet;
5
{'name': 'Earth', 'orderFromSun': 3, ...}
crudRead.go
1// find code goes here
2filter := 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}
14cursor, err := coll.Find(context.TODO(), filter)
15if err != nil {
16 panic(err)
17}
map[name:Earth orderFromSun:3 ...]
CrudRead.java
1// find code goes here
2Bson filter = and(lt("surfaceTemperatureC.mean", 15), gt("surfaceTemperatureC.min", -100));
3MongoCursor<Document> cursor = coll.find(filter).iterator();
{'name': 'Earth', 'orderFromSun': 3, ...}
crud-read.js
1// find code goes here
2const 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查询运算符。

crud-read.js
1const cursor = coll.find({
2 $and: [{ orderFromSun: { $gt: 2 } }, { orderFromSun: { $lt: 5 } }],
3});
{'name': 'Mars', 'orderFromSun': 4, ... }
{'name': 'Earth', 'orderFromSun': 3, ... }
crud_read.py
1cursor = coll.find(
2 {"$and": [{"orderFromSun": {"$gt": 2}}, {"orderFromSun": {"$lt": 5}}]}
3)
{'name': 'Mars', 'orderFromSun': 4, ... }
{'name': 'Earth', 'orderFromSun': 3, ... }

如果您不使用$and运算符,驱动程序在查询过滤器中遇到相同的键多次,并使用最后遇到的键。尝试省略$and运算符,看看会发生什么。

crud_read.py
1# find code goes here
2cursor = coll.find(
3 {"surfaceTemperatureC.mean": {"$lt": 15}, "surfaceTemperatureC.min": {"$gt": -100}}
4)
{'name': 'Earth', 'orderFromSun': 3, ...}

注意

隐式AND

指定多个条件很常见。如果您没有指定任何查询运算符,驱动程序将您的条件解释为AND关系。但是,有时在指定多个条件时必须明确,尤其是在指定同一字段的条件时。

例如,为了找到planets集合中orderFromSun值大于2且小于5的文档,您必须使用$and查询运算符。

crud-read.js
1const cursor = coll.find({
2 $and: [{ orderFromSun: { $gt: 2 } }, { orderFromSun: { $lt: 5 } }],
3});
{'name': 'Mars', 'orderFromSun': 4, ... }
{'name': 'Earth', 'orderFromSun': 3, ... }
crud_read.py
1cursor = coll.find(
2 {"$and": [{"orderFromSun": {"$gt": 2}}, {"orderFromSun": {"$lt": 5}}]}
3)
{'name': 'Mars', 'orderFromSun': 4, ... }
{'name': 'Earth', 'orderFromSun': 3, ... }

如果您不使用$and运算符,驱动程序在查询过滤器中遇到相同的键多次,并使用最后遇到的键。尝试省略$and运算符,看看会发生什么。

2

当您想要指定互斥的条件时,需要使用OR查询。例如,您不能匹配在planets集合中orderFromSun值既大于7又小于2的文档。

以下示例展示了如何使用$or运算符来表达互斥的条件。

CrudRead.cs
1// find code goes here
2var 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, ... }
crudRead.go
1// find code goes here
2filter := 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
13cursor, err := coll.Find(context.TODO(), filter)
14if err != nil {
15 panic(err)
16}
map[name:Mercury orderFromSun:1 ...]
map[name:Neptune orderFromSun:8 ...]
CrudRead.java
1// find code goes here
2Bson filter = or(gt("orderFromSun", 7), lt("orderFromSun", 2));
3MongoCursor<Document> cursor = coll.find(filter).iterator();
{ name: 'Mercury', orderFromSun: 1, ... }
{ name: 'Neptune', orderFromSun: 8, ... }
crud-read.js
1// find code goes here
2const cursor = coll.find({
3 $or: [{ orderFromSun: { $gt: 7 } }, { orderFromSun: { $lt: 2 } }],
4});
{ name: 'Mercury', orderFromSun: 1, ... }
{ name: 'Neptune', orderFromSun: 8, ... }
crud_read.py
1# find code goes here
2cursor = 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。

接下来是什么
将数据插入MongoDB
15分钟

在MongoDB中创建和插入文档。

开始指南
章节2
CRUD
  • 添加MongoDB驱动程序
  • 在MongoDB中读取数据
  • 使用查询从MongoDB中读取数据
  • 使用运算符和组合查询读取数据
  • 将数据插入MongoDB
  • 在MongoDB中更新数据
  • 从MongoDB中删除数据