“文档” 菜单
文档首页
/
MongoDB 阿特拉斯
/ /

如何使用 Atlas Search 检查空值和非空值

在此页面上

  • 插入样本数据
  • 使用动态映射创建 Atlas Search 索引
  • 检查 null
  • 查找所有非null

本教程介绍如何使用 Atlas Search 查询来检查数据中的 null 或非 null 值。它将引导您完成以下步骤:

  • 将具有 null 值和缺失字段的示例文档加载到 sample_mflix.users 集合中。

  • sample_mflix.users集合设置具有动态映射的 Atlas Search 索引。

  • 运行 Atlas Search 查询以查找 sample_mflix.users 集合中 password 字段具有 null 值的所有文档。

    注意

    要成功检查有无 null 值,您正在查询的字段不能包含多态数据。在此示例中,sample_mflix.users 集合中所有文档的 password 字段的数据类型均为 string

  • 运行 Atlas Search 查询以查找 sample_mflix.users 集合中 password 字段不含 null 值的所有文档。

开始之前,请确保 Atlas 集群满足先决条件中所述的要求。

要创建 Atlas Search 索引,您必须拥有 Project Data Access Admin 或更高的项目访问权限。

在本节中,您将向 sample_mflix.users 集合添加包含 null 值和缺失字段的示例文档。有了这些附加文件,您就可以在本教程中成功运行 null 和非 null 值的示例查询。

1
  1. 如果尚未显示,请选择包含所需项目的组织导航栏中的Organizations菜单。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。

2

单击集群的对应 Browse Collections 按钮。

3
  1. sample_mflix 数据库中,选择 users 集合。

  2. 单击 Insert Document(连接)。

  3. 单击 JSON 视图 ({}) 替换默认文档。

  4. 一次一个,复制并粘贴以下样本文档,然后单击 Insert(插入)将文档添加到集合中。

    { "name": "Andre Robinson", "email": "andre.robinson@example.com", "password": null }
    { "name": "Laura Garcia", "email": "lgarcia@example.net" }

在本节中,您将创建一个 Atlas Search 索引,该索引使用动态映射sample_mflix.users 集合中的所有可动态索引字段动态创建索引。

1
  1. 如果尚未显示,请选择包含所需项目的组织导航栏中的Organizations菜单。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。

2

您可以从侧边栏、 Data Explorer或集群详细信息页面转到 Atlas Search 页面。

  1. 在侧边栏中,单击Services标题下的Atlas Search

  2. Select data source下拉列表中,选择您的集群并单击Go to Atlas Search

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击集合的Search Indexes标签页。

  1. 单击集群名称。

  2. 单击 Atlas Search 标签页。

3
4
  • 要获得引导式体验,请选择 Atlas Search Visual Editor

  • 要编辑原始索引定义,请选择 Atlas SearchJSON Editor

5
  1. Index Name 字段中输入 null-check-tutorial

    注意

    如果将索引命名为 default,则在使用 $search 管道阶段时,您无需指定 index 参数。否则,您必须使用 index 参数指定索引名称。

  2. Database and Collection(数据库和集合)部分中找到 sample_mflix 数据库,然后选择 users 集合。

6

您可以创建使用动态映射静态映射的 Atlas Search 索引。要了解有关动态和静态映射的更多信息,请参阅静态和动态映射

以下索引定义对 movies 集合中的支持类型字段动态创建索引。您可以使用 Atlas Search Visual Editor 或 Atlas Search JSON Editor 在 Atlas 用户界面中创建索引。

  1. 单击 Next(连接)。

  2. 查看 movies 集合的 "default" 索引定义。

  1. 单击 Next(连接)。

  2. 查看索引定义。

    索引定义应类似于以下内容:

    {
    "mappings": {
    "dynamic": true
    }
    }

    上述索引定义对 movies 集合中每个文档中的支持类型字段动态创建索引。

  3. 单击 Next(连接)。

7
8

此时将显示一个模态窗口,让您知道索引正在构建中。点击 Close 按钮。

9

构建索引大约需要一分钟时间。在构建时,Status 列显示 Build in Progress。构建完成后,Status 列显示 Active


➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。


设置 Atlas Search 索引后,可以连接到 Atlas 集群并对 sample_mflix.users 集合中的字段运行查询。以下查询使用复合通配符操作符来查找所有具有 password 字段值为 null 的文档。

注意

我们不建议使用通配符操作符来查询索引大小较大的集合。 要了解更多信息并投票支持 Atlas Search 增强功能以支持空数据类型的索引和查询,请使用 MongoDB 反馈引擎。

1
  1. 如果尚未显示,请选择包含所需项目的组织导航栏中的Organizations菜单。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。

2

您可以从侧边栏、 Data Explorer或集群详细信息页面转到 Atlas Search 页面。

  1. 在侧边栏中,单击Services标题下的Atlas Search

  2. Select data source下拉列表中,选择您的集群并单击Go to Atlas Search

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击集合的Search Indexes标签页。

  1. 单击集群名称。

  2. 单击 Atlas Search 标签页。

3

单击要查询的索引右侧的 Query 按钮。

4

单击Edit Query可查看JSON格式的默认查询语法示例。

5

以下查询使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

  • must 子句以仅查找具有password字段的文档。

  • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

[
{
"$search": {
index: "null-check-tutorial",
"compound": {
"must": {
"exists": {
"path": "password"
}
},
"mustNot": {
"wildcard": {
"path": "password",
"query": "*",
"allowAnalyzedField": true
}
}
}
}
}
]
SCORE: 1 _id: "64a6e2e5bceafd4df9153bab"
name: "Andre Robinson"
email: "andre.robinson@example.com"
password: null
1

在终端窗口中打开mongosh并连接到集群。 有关连接的详细说明,请参阅通过mongosh连接。

2

mongosh 提示符下运行以下命令:

use sample_mflix
3

以下查询使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

  • must 子句以仅查找具有password字段的文档。

  • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

db.users.aggregate([
{
$search: {
"index": "null-check-tutorial",
"compound": {
"must": {
"exists": {
"path": "password"
}
},
"mustNot": {
"wildcard": {
"path": "password",
"query": "*",
"allowAnalyzedField": true
}
}
}
}
}
])
{
_id: ObjectId("63c84590975d5c7c8bf1ebed"),
name: 'Andre Robinson',
email: 'andre.robinson@example.com',
password: null
}
1

打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。

2

Databases 屏幕上,依次单击 sample_mflix 数据库和 users 集合。

3

以下查询使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

  • must 子句以仅查找具有password字段的文档。

  • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

若要在 MongoDB Compass 中运行此查询:

  1. 单击 Aggregations 标签页。

  2. 单击Select... ,然后从下拉列表中选择$search阶段并为该阶段添加查询,以配置以下管道阶段。

    管道阶段
    查询
    $search
    {
    "index": "null-check-tutorial",
    "compound": {
    "must": {
    "exists": {
    "path": "password"
    }
    },
    "mustNot": {
    "wildcard": {
    "path": "password",
    "query": "*",
    "allowAnalyzedField": true
    }
    }
    }
    }

如果启用了 Auto Preview,MongoDB Compass 将在 $search 管道阶段旁边显示以下文档:

1{
2 _id: ObjectId("63c84590975d5c7c8bf1ebed"),
3 name: 'Andre Robinson',
4 email: 'andre.robinson@example.com',
5 password: null
6}
1
  1. 创建一个名为is-null-query-example的新目录,并使用dotnet new命令初始化项目。

    mkdir is-null-query-example
    cd is-null-query-example
    dotnet new console
  2. 将 .NET/C# 驱动程序作为依赖项添加到项目中。

    dotnet add package MongoDB.Driver
2

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

    • must 子句以仅查找具有password字段的文档。

    • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

  • 遍历游标以打印与查询匹配的文档。

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class IsNullQuery
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our UserDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
20 var usersCollection = mflixDatabase.GetCollection<UserDocument>("users");
21
22 // define and run pipeline
23 var results = usersCollection.Aggregate()
24 .Search(Builders<UserDocument>.Search.Compound()
25 .Must(Builders<UserDocument>.Search.Exists(user => user.Password))
26 .MustNot(Builders<UserDocument>.Search.Wildcard(user => user.Password, "*", true)),
27 indexName: "null-check-tutorial")
28 .ToList();
29
30 // print results
31 foreach (var user in results)
32 {
33 Console.WriteLine(user.ToJson());
34 }
35 }
36}
37
38[BsonIgnoreExtraElements]
39public class UserDocument
40{
41 [BsonIgnoreIfDefault]
42 public ObjectId Id { get; set; }
43 public string Name { get; set; }
44 public string Email { get; set; }
45 public string Password { get; set; }
46}

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3

运行dotnet run命令后,程序会将以下文档打印到终端:

dotnet run Program.cs
1{
2 "_id" : ObjectId("63d02602e69635364a445f3b"),
3 "name" : "Andre Robinson",
4 "email" : "andre.robinson@example.com",
5 "password" : null
6}
1
2

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

    • must 子句以仅查找具有password字段的文档。

    • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

  • 遍历游标以打印与查询匹配的文档。

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 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19 // set namespace
20 collection := client.Database("sample_mflix").Collection("users")
21 // define pipeline stages
22 searchStage := bson.D{{"$search", bson.D{{"index", "null-check-tutorial"}, {"compound", bson.D{{"must", bson.D{{"exists", bson.D{{"path", "password"}}}}}, {"mustNot", bson.D{{"wildcard", bson.D{{"path", "password"}, {"query", "*"}, {"allowAnalyzedField", true}}}}}}}}}}
23 // run pipeline
24 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage})
25 if err != nil {
26 panic(err)
27 }
28 // print results
29 var results []bson.D
30 if err = cursor.All(context.TODO(), &results); err != nil {
31 panic(err)
32 }
33 for _, result := range results {
34 fmt.Println(result)
35 }
36}

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3
go run isnull-query.go
[
{_id ObjectID("63c84590975d5c7c8bf1ebed")}
{name Andre Robinson}
{email andre.robinson@example.com}
{password <nil>}
]
1
junit
4.11 或更高版本
mongodb-driver-sync
4.3.0 或更高版本
slf4j-log4j12
1.7.30 或更高版本
2
3

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

    • must 子句以仅查找具有password字段的文档。

    • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

  • 遍历游标以打印与查询匹配的文档。

1import static com.mongodb.client.model.Aggregates.limit;
2import static com.mongodb.client.model.Aggregates.project;
3import static com.mongodb.client.model.Projections.excludeId;
4import static com.mongodb.client.model.Projections.fields;
5import static com.mongodb.client.model.Projections.include;
6import com.mongodb.client.MongoClient;
7import com.mongodb.client.MongoClients;
8import com.mongodb.client.MongoCollection;
9import com.mongodb.client.MongoDatabase;
10import org.bson.Document;
11import java.util.Arrays;
12
13public class IsNullQuery {
14
15 public static void main(String[] args) {
16 // connect to your Atlas cluster
17 String uri = "<connection-string>";
18
19 try (MongoClient mongoClient = MongoClients.create(uri)) {
20 // set namespace
21 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
22 MongoCollection<Document> collection = database.getCollection("users");
23
24 // define pipeline
25 Document agg = new Document("$search",
26 new Document ("index", "null-check-tutorial")
27 .append("compound",
28 new Document("must",
29 new Document("exists",
30 new Document("path", "password")))
31 .append("mustNot",
32 new Document("wildcard",
33 new Document("path", "password")
34 .append("query", "*")
35 .append("allowAnalyzedField", true)))));
36 // run pipeline and print results
37 collection.aggregate(Arrays.asList(agg)).forEach(doc -> System.out.println(doc.toJson()));
38 }
39 }
40}

注意

要在 Maven 环境中运行示例代码,请在您的声明中的 import 文件上方添加以下内容。

package com.mongodb.drivers;

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

4
javac IsNullQuery.java
java IsNullQuery
{
"_id": {"$oid": "63c84590975d5c7c8bf1ebed"},
"name": "Andre Robinson",
"email": "andre.robinson@example.com",
"password": null
}
1
mongodb-driver-kotlin-coroutine
4.10.0 或更高版本
2
3

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

    • must 子句以仅查找具有password字段的文档。

    • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

  • 遍历游标以打印与查询匹配的文档。

1import com.mongodb.kotlin.client.coroutine.MongoClient
2import kotlinx.coroutines.runBlocking
3import org.bson.Document
4
5fun main() {
6 // connect to your Atlas cluster
7 val uri = "<connection-string>"
8 val mongoClient = MongoClient.create(uri)
9
10 // set namespace
11 val database = mongoClient.getDatabase("sample_mflix")
12 val collection = database.getCollection<Document>("users")
13
14 runBlocking {
15 // define pipeline
16 val agg = Document(
17 "\$search",
18 Document("index", "null-check-tutorial")
19 .append(
20 "compound",
21 Document(
22 "must",
23 Document(
24 "exists",
25 Document("path", "password")
26 )
27 )
28 .append(
29 "mustNot",
30 Document(
31 "wildcard",
32 Document("path", "password")
33 .append("query", "*")
34 .append("allowAnalyzedField", true)
35 )
36 )
37 )
38 )
39
40 // run pipeline and print results
41 val resultsFlow = collection.aggregate<Document>(
42 listOf(agg)
43 )
44 resultsFlow.collect { println(it) }
45 }
46
47 mongoClient.close()
48}

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

4

当您在 IDE 中运行IsNullQuery.kt程序时,它会打印以下文档:

Document{{_id=65e0cea967e8cd48b48be599, name=Andre Robinson, email=andre.robinson@example.com, password=null}}
1
2

此代码示例将执行以下任务:

  • 导入 mongodb,即 MongoDB 的 Node.js 驱动程序。

  • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

  • 使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

    • must 子句以仅查找具有password字段的文档。

    • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

  • 遍历游标以打印与查询匹配的文档。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas cluster
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12
13 // set namespace
14 const database = client.db("sample_mflix");
15 const coll = database.collection("users");
16
17 // define pipeline
18 const agg = [{
19 '$search': {
20 'index': 'null-check-tutorial',
21 'compound': {
22 'must': {
23 'exists': {
24 'path': 'password'
25 }
26 },
27 'mustNot': {
28 'wildcard': {
29 'path': 'password',
30 'query': '*',
31 'allowAnalyzedField': true
32 }
33 }
34 }
35 }
36 }];
37 // run pipeline
38 const result = await coll.aggregate(agg);
39
40 // print results
41 await result.forEach((doc) => console.log(doc));
42 } finally {
43 await client.close();
44 }
45}
46run().catch(console.dir);

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3
node isnull-query.js
{
_id: ObjectId("63c84590975d5c7c8bf1ebed"),
name: 'Andre Robinson',
email: 'andre.robinson@example.com',
password: null
}
1
2

此代码示例将执行以下任务:

  • 导入pymongo 、MongoDB 的 Python 驱动程序和dns模块,这是使用DNS种子列表连接字符串将pymongo连接到Atlas所必需的。

  • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

  • 使用 $search 管道阶段查询该集合。该查询使用了以下复合运算符子句:

    • must 子句以仅查找具有password字段的文档。

    • mustNot 带有通配符操作符的子句,以排除在password字段中具有任何值的所有文档。

  • 遍历游标以打印与查询匹配的文档。

1import pymongo
2
3# connect to your Atlas cluster
4client = pymongo.MongoClient('<connection-string>')
5
6# define pipeline
7pipeline = [{
8 '$search': {
9 'index': 'null-check-tutorial',
10 'compound': {
11 'must': {
12 'exists': {
13 'path': 'password'
14 }
15 },
16 'mustNot': {
17 'wildcard': {
18 'path': 'password',
19 'query': '*',
20 'allowAnalyzedField': True
21 }
22 }
23 }
24 }
25}]
26# run pipeline
27result = client["sample_mflix"]["users"].aggregate(pipeline)
28
29# print results
30for i in result:
31 print(i)

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3
python isnull-query.py
{
'_id': ObjectId('63c84590975d5c7c8bf1ebed'),
'name': 'Andre Robinson',
'email': 'andre.robinson@example.com',
'password': None
}

Atlas Search 返回一个 password 值为 null 的文档。Atlas Search 不包含缺少 password 字段的文档,因为查询指定 password 字段必须存在。


➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。


设置 Atlas Search 索引后,您可以连接到 Atlas 集群并对 sample_mflix.users 集合中的字段运行查询。以下查询使用复合运算符和通配符来查找在 password 字段中没有 null 值或没有 password 字段的文档。

1
  1. 如果尚未显示,请选择包含所需项目的组织导航栏中的Organizations菜单。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。

2

您可以从侧边栏、 Data Explorer或集群详细信息页面转到 Atlas Search 页面。

  1. 在侧边栏中,单击Services标题下的Atlas Search

  2. Select data source下拉列表中,选择您的集群并单击Go to Atlas Search

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击集合的Search Indexes标签页。

  1. 单击集群名称。

  2. 单击 Atlas Search 标签页。

3

单击要查询的索引右侧的 Query 按钮。

4

单击Edit Query可查看JSON格式的默认查询语法示例。

5

以下查询仅搜索在 password 字段中没有 null 值的用户。查询的具体内容如下:

  • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

  • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

    注意

    Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

[
{
$search: {
"index": "null-check-tutorial",
"compound": {
"should": [{
"wildcard": {
"path": "password",
"query": "*",
"allowAnalyzedField": true
}
},
{
"compound": {
"mustNot": {
"exists": {
"path": "password"
}
},
"score": { "constant": { "value": 2 } }
}
}
]
}
}
}
]
SCORE: 2 _id: "64a6e2f2bceafd4df9153eaf”
name: "Laura Garcia"
email: "lgarcia@example.net"
SCORE: 1 _id: "59b99db4cfa9a34dcd7885b6”
name: "Ned Stark"
email: "sean_bean@gameofthron.es"
password: "$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu"
SCORE: 1 _id: "59b99db4cfa9a34dcd7885b7”
name: "Robert Baratheon"
email: "mark_addy@gameofthron.es"
password: "$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y"
SCORE: 1 _id: "59b99db5cfa9a34dcd7885b8”
name: "Jaime Lannister"
email: "nikolaj_coster-waldau@gameofthron.es"
password: "$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK"
SCORE: 1 _id: "59b99db5cfa9a34dcd7885b9”
name: "Catelyn Stark"
email: "michelle_fairley@gameofthron.es"
password: "$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS"
SCORE: 1 _id: "59b99db6cfa9a34dcd7885ba”
name: "Cersei Lannister"
email: "lena_headey@gameofthron.es"
password: "$2b$12$FExjgr7CLhNCa.oUsB9seub8mqcHzkJCFZ8heMc8CeIKOZfeTKP8m"
SCORE: 1 _id: "59b99db6cfa9a34dcd7885bb”
name: "Daenerys Targaryen"
email: "emilia_clarke@gameofthron.es"
password: "$2b$12$NzpbWHdMytemLtTfFKduHenr2NZ.rvxIKuYM4AWLTFaUShxbJ.G3q"
SCORE: 1 _id: "59b99db6cfa9a34dcd7885bc”
name: "Jorah Mormont"
email: "iain_glen@gameofthron.es"
password: "$2b$12$K8bKkwnpkrjsBPzASZxO/.yj7d9kvupiVtO6JA3Xl106AKXr3pXFK"
SCORE: 1 _id: "59b99db7cfa9a34dcd7885bd”
name: "Petyr Baelish"
email: "aidan_gillen@gameofthron.es"
password: "$2b$12$qM.YvmiekyYYY7p7phpK3OicbRCDkN7ESwYAnG/o9YnfHC0Mhkmbi"
SCORE: 1 _id: "59b99db8cfa9a34dcd7885be”
name: "Viserys Targaryen"
email: "harry_lloyd@gameofthron.es"
password: "$2b$12$cpwVmU4DyuQxgwpdrVJhaudzbKOXlHRbf.tpCuHjpAqonuoyvvEG6"
1

在终端窗口中打开mongosh并连接到集群。 有关连接的详细说明,请参阅通过mongosh连接。

2

mongosh 提示符下运行以下命令:

use sample_mflix
3

以下查询仅搜索在 password 字段中没有 null 值的用户。查询包括以下管道阶段:

  • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

    • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

    • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

      注意

      Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段到:

    • 排除除 namepassword 之外的所有字段。

    • 添加一个 score 字段。

db.users.aggregate([
{
$search: {
"index": "null-check-tutorial",
"compound": {
"should": [{
"wildcard": {
"path": "password",
"query": "*",
"allowAnalyzedField": true
}
},
{
"compound": {
"mustNot": {
"exists": {
"path": "password"
}
},
"score": { "constant": { "value": 2 } }
}
}
]
}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 0,
"name": 1,
"password": 1,
"score": { "$meta": "searchScore" }
}
}
])
{ name: 'Laura Garcia', score: 2 },
{
name: 'Ned Stark',
password: '$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu',
score: 1
},
{
name: 'Robert Baratheon',
password: '$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y',
score: 1
},
{
name: 'Jaime Lannister',
password: '$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK',
score: 1
},
{
name: 'Catelyn Stark',
password: '$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS',
score: 1
}
1

打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。

2

Databases 屏幕上,依次单击 sample_mflix 数据库和 users 集合。

3

查询使用了下列管道阶段:

  • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

    • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

    • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

      注意

      Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段到:

    • 排除除 namepassword 之外的所有字段。

    • 添加一个 score 字段。

若要在 MongoDB Compass 中运行此查询:

  1. 单击 Aggregations 标签页。

  2. 单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。

    管道阶段
    查询
    $search
    {
    "index": "null-check-tutorial",
    "compound": {
    "should": [{
    "wildcard": {
    "path": "password",
    "query": "*",
    "allowAnalyzedField": true
    }
    },
    {
    "compound": {
    "mustNot": {
    "exists": {
    "path": "password"
    }
    },
    "score": { "constant": { "value": 2 } }
    }
    }
    ]
    }
    }
    $limit
    5
    $project
    {
    "_id": 0,
    "name": 1,
    "password": 1,
    "score": { "$meta": "searchScore" }
    }

如果启用了 Auto Preview,MongoDB Compass 将在 $project 管道阶段旁边显示以下文档:

1{ name: 'Laura Garcia', score: 2 },
2{
3 name: 'Ned Stark',
4 password: '$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu',
5 score: 1
6},
7{
8 name: 'Robert Baratheon',
9 password: '$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y',
10 score: 1
11},
12{
13 name: 'Jaime Lannister',
14 password: '$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK',
15 score: 1
16},
17{
18 name: 'Catelyn Stark',
19 password: '$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS',
20 score: 1
21}
1
  1. 创建一个名为not-null-query-example的新目录,并使用dotnet new命令初始化项目。

    mkdir not-null-query-example
    cd not-null-query-example
    dotnet new console
  2. 将 .NET/C# 驱动程序作为依赖项添加到项目中。

    dotnet add package MongoDB.Driver
2

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用以下管道阶段:

    • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

      • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

      • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

        注意

        Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

    • $limit 阶段将输出限制为 5 个结果。

    • $project 阶段到:

      • 排除除 namepassword 之外的所有字段。

      • 添加一个 score 字段。

  • 遍历游标以打印与查询匹配的文档。

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class NotNullQuery
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our UserDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
20 var usersCollection = mflixDatabase.GetCollection<UserDocument>("users");
21
22 // define a builder for the search score
23 var scoreBuilder = new SearchScoreDefinitionBuilder<UserDocument>();
24
25 // define and run pipeline
26 var results = usersCollection.Aggregate()
27 .Search(Builders<UserDocument>.Search.Compound()
28 .Should(Builders<UserDocument>.Search.Wildcard(user => user.Password, "*", true))
29 .Should(Builders<UserDocument>.Search.Compound(scoreBuilder.Constant(2))
30 .MustNot(Builders<UserDocument>.Search.Exists(user => user.Password))),
31 indexName: "null-check-tutorial")
32 .Limit(5)
33 .Project<UserDocument>(Builders<UserDocument>.Projection
34 .Include(user => user.Name)
35 .Include(user => user.Password)
36 .MetaSearchScore(user => user.Score)
37 .Exclude(user => user.Id))
38 .ToList();
39
40 // print results
41 foreach (var user in results)
42 {
43 Console.WriteLine(user.ToJson());
44 }
45 }
46}
47
48[BsonIgnoreExtraElements]
49public class UserDocument
50{
51 [BsonIgnoreIfDefault]
52 public string Id { get; set; }
53 public string Name { get; set; }
54 [BsonIgnoreIfDefault]
55 public string Password { get; set; }
56 public double Score { get; set; }
57}

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3

运行dotnet run命令后,程序会将以下文档打印到终端:

dotnet run Program.cs
{ "name" : "Laura Garcia", "score" : 2.0 }
{ "name" : "Ned Stark", "password" : "$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu", "score" : 1.0 }
{ "name" : "Robert Baratheon", "password" : "$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y", "score" : 1.0 }
{ "name" : "Jaime Lannister", "password" : "$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK", "score" : 1.0 }
{ "name" : "Catelyn Stark", "password" : "$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS", "score" : 1.0 }
1
2

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用以下管道阶段:

    • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

      • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

      • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

        注意

        Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

    • $limit 阶段将输出限制为 5 个结果。

    • $project 阶段到:

      • 排除除 namepassword 之外的所有字段。

      • 添加一个 score 字段。

  • 遍历游标以打印与查询匹配的文档。

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 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19 // set namespace
20 collection := client.Database("sample_mflix").Collection("users")
21 // define pipeline stages
22 searchStage := bson.D{{"$search", bson.D{
23 {"index", "null-check-tutorial"},
24 {"compound", bson.D{{
25 "should", bson.A{bson.D{{
26 "wildcard", bson.D{
27 {"path", "password"},
28 {"query", "*"},
29 {"allowAnalyzedField", true}}}}, bson.D{{
30 "compound", bson.D{{
31 "mustNot", bson.D{{
32 "exists", bson.D{
33 {"path", "password"}}}}},
34 {"score", bson.D{{"constant", bson.D{{"value", 2}}}}},
35 }}}}}}}}}}
36 projectStage := bson.D{{"$project", bson.D{{"name", 1}, {"password", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
37 limitStage := bson.D{{"$limit", 5}}
38 // run pipeline
39 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage, limitStage})
40 if err != nil {
41 panic(err)
42 }
43 // print results
44 var results []bson.D
45 if err = cursor.All(context.TODO(), &results); err != nil {
46 panic(err)
47 }
48 for _, result := range results {
49 fmt.Println(result)
50 }
51}

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3
go run notnull-query.go
[{name Laura Garcia} {score 2}]
[{name Ned Stark} {password $2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu} {score 1}]
[{name Robert Baratheon} {password $2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y} {score 1}]
[{name Jaime Lannister} {password $2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK} {score 1}]
[{name Catelyn Stark} {password $2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS} {score 1}]
1
junit
4.11 或更高版本
mongodb-driver-sync
4.3.0 或更高版本
slf4j-log4j12
1.7.30 或更高版本
2
3

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用以下管道阶段:

    • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

      • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

      • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

        注意

        Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

    • $limit 阶段将输出限制为 5 个结果。

    • $project 阶段到:

      • 排除除 namepassword 之外的所有字段。

      • 添加一个 score 字段。

  • 遍历游标以打印与查询匹配的文档。

1import static com.mongodb.client.model.Aggregates.limit;
2import static com.mongodb.client.model.Aggregates.project;
3import static com.mongodb.client.model.Projections.*;
4import com.mongodb.client.MongoClient;
5import com.mongodb.client.MongoClients;
6import com.mongodb.client.MongoCollection;
7import com.mongodb.client.MongoDatabase;
8import org.bson.Document;
9import java.util.Arrays;
10
11public class NotNullQuery {
12
13 public static void main(String[] args) {
14 // connect to your Atlas cluster
15 String uri = "<connection-string>";
16
17 try (MongoClient mongoClient = MongoClients.create(uri)) {
18 // set namespace
19 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
20 MongoCollection<Document> collection = database.getCollection("users");
21
22 // define pipeline
23 Document agg = new Document("$search",
24 new Document ("index", "null-check-tutorial")
25 .append("compound",
26 new Document("should", Arrays.asList(
27 new Document("wildcard",
28 new Document("path", "password")
29 .append("query", "*")
30 .append("allowAnalyzedField", true)),
31 new Document("compound",
32 new Document("mustNot",
33 new Document("exists",
34 new Document("path", "password")))
35 .append("score",
36 new Document("constant",
37 new Document("value", 2L))))))));
38
39 // run pipeline and print results
40 collection.aggregate(Arrays.asList(agg,
41 limit(5),
42 project(fields(
43 excludeId(),
44 include("name", "password"),
45 computed("score", new Document("$meta", "searchScore"))))))
46 .forEach(doc -> System.out.println(doc.toJson()));
47 }
48 }
49}

注意

要在 Maven 环境中运行示例代码,请在您的声明中的 import 文件上方添加以下内容。

package com.mongodb.drivers;

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

4
javac NotNullQuery.java
java NotNullQuery
{"name": "Laura Garcia", "score": 2.0}
{"name": "Ned Stark", "password": "$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu", "score": 1.0}
{"name": "Robert Baratheon", "password": "$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y", "score": 1.0}
{"name": "Jaime Lannister", "password": "$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK", "score": 1.0}
{"name": "Catelyn Stark", "password": "$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS", "score": 1.0}
1
mongodb-driver-kotlin-coroutine
4.10.0 或更高版本
2
3

此代码示例将执行以下任务:

  • 导入mongodb包和依赖项。

  • 建立与您的 Atlas 集群的连接。

  • 使用以下管道阶段:

    • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

      • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

      • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

        注意

        Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

    • $limit 阶段将输出限制为 5 个结果。

    • $project 阶段到:

      • 排除除 namepassword 之外的所有字段。

      • 添加一个 score 字段。

  • 遍历游标以打印与查询匹配的文档。

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // connect to your Atlas cluster
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12
13 // set namespace
14 val database = mongoClient.getDatabase("sample_mflix")
15 val collection = database.getCollection<Document>("users")
16
17 runBlocking {
18 // define pipeline
19 val agg = Document(
20 "\$search",
21 Document("index", "null-check-tutorial")
22 .append(
23 "compound",
24 Document(
25 "should", listOf(
26 Document(
27 "wildcard",
28 Document("path", "password")
29 .append("query", "*")
30 .append("allowAnalyzedField", true)
31 ),
32 Document(
33 "compound",
34 Document(
35 "mustNot",
36 Document(
37 "exists",
38 Document("path", "password")
39 )
40 )
41 .append(
42 "score",
43 Document(
44 "constant",
45 Document("value", 2L)
46 )
47 )
48 )
49 )
50 )
51 )
52 )
53
54 // run pipeline and print results
55 val resultsFlow = collection.aggregate<Document>(
56 listOf(
57 agg,
58 limit(5),
59 project(fields(
60 excludeId(),
61 include("name", "password"),
62 computed("score", Document("\$meta", "searchScore"))))
63 )
64 )
65 resultsFlow.collect { println(it) }
66 }
67
68 mongoClient.close()
69}

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

4

当你在 IDE 中运行 NotNullQuery.kt 程序时,它会打印以下文档:

Document{{name=Laura Garcia, score=2.0}}
Document{{name=Ned Stark, password=$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu, score=1.0}}
Document{{name=Robert Baratheon, password=$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y, score=1.0}}
Document{{name=Jaime Lannister, password=$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK, score=1.0}}
Document{{name=Catelyn Stark, password=$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS, score=1.0}}
1
2

此代码示例将执行以下任务:

  • 导入 mongodb,即 MongoDB 的 Node.js 驱动程序。

  • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

  • 使用以下管道阶段:

    • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

      • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

      • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

        注意

        Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

    • $limit 阶段将输出限制为 5 个结果。

    • $project 阶段到:

      • 排除除 namepassword 之外的所有字段。

      • 添加一个 score 字段。

  • 遍历游标以打印与查询匹配的文档。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas cluster
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12
13 // set namespace
14 const database = client.db("sample_mflix");
15 const coll = database.collection("users");
16
17 // define pipeline
18 const agg = [
19 {
20 '$search': {
21 'index': 'null-check-tutorial',
22 'compound': {
23 'should': [{
24 'wildcard': {
25 'path': 'password',
26 'query': '*',
27 'allowAnalyzedField': true
28 }
29 },
30 {
31 'compound': {
32 'mustNot': {
33 'exists': {
34 'path': 'password'
35 }
36 },
37 'score': { 'constant': { 'value': 2 } }
38 }
39 }]
40 }
41 }
42 },
43 {
44 '$limit': 5
45 },
46 {
47 '$project': {'_id': 0, 'name': 1, 'password': 1, 'score': { '$meta': 'searchScore' }}
48 }
49 ];
50 // run pipeline
51 const result = await coll.aggregate(agg);
52
53 // print results
54 await result.forEach((doc) => console.log(doc));
55 } finally {
56 await client.close();
57 }
58}
59run().catch(console.dir);

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3
node notnull-query.js
{ name: 'Laura Garcia', score: 2 }
{
name: 'Ned Stark',
password: '$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu',
score: 1
}
{
name: 'Robert Baratheon',
password: '$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y',
score: 1
}
{
name: 'Jaime Lannister',
password: '$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK',
score: 1
}
{
name: 'Catelyn Stark',
password: '$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS',
score: 1
}
1
2

此代码示例将执行以下任务:

  • 导入pymongo 、MongoDB 的 Python 驱动程序和dns模块,这是使用DNS种子列表连接字符串将pymongo连接到Atlas所必需的。

  • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

  • 使用以下管道阶段:

    • 用于查询集合的 $search 管道阶段。查询使用复合操作符 should 子句执行以下操作:

      • 使用通配符操作符,查找所有 password 字段没有 null 值的文档。

      • 使用复合运算符 mustNot 子句查找没有 password 字段的文档,并使用 constant 选项将其 score 替换为 2

        注意

        Atlas Search 按从最高分到最低分的顺序返回文档。在本例中,您将改变缺少 password 字段的文档的分数,使其优先返回。否则,这些文档的分数为 0,最后返回。要了解更多信息,请参阅评分。

    • $limit 阶段将输出限制为 5 个结果。

    • $project 阶段到:

      • 排除除 namepassword 之外的所有字段。

      • 添加一个 score 字段。

  • 遍历游标以打印与查询匹配的文档。

1import pymongo
2
3# connect to your Atlas cluster
4client = pymongo.MongoClient('<connection-string>')
5
6# define pipeline
7pipeline = [{
8 '$search': {
9 'index': 'null-check-tutorial',
10 'compound': {
11 'should': [
12 {
13 'wildcard': {
14 'path': 'password',
15 'query': '*',
16 'allowAnalyzedField': True
17 }
18 }, {
19 'compound': {
20 'mustNot': {
21 'exists': {
22 'path': 'password'
23 }
24 },
25 'score': {
26 'constant': {
27 'value': 2
28 }
29 }
30 }
31 }
32 ]
33 }
34 }
35 }, {
36 '$project': {
37 '_id': 0,
38 'name': 1,
39 'password': 1,
40 'score': {
41 '$meta': 'searchScore'
42 }
43 }
44 }, {
45 '$limit': 5
46 }
47]
48# run pipeline
49result = client["sample_mflix"]["users"].aggregate(pipeline)
50
51# print results
52for i in result:
53 print(i)

在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

3
python notnull-query.py
{'name': 'Laura Garcia', 'score': 2.0}
{'name': 'Ned Stark', 'password': '$2b$12$UREFwsRUoyF0CRqGNK0LzO0HM/jLhgUCNNIJ9RJAqMUQ74crlJ1Vu', 'score': 1.0}
{'name': 'Robert Baratheon', 'password': '$2b$12$yGqxLG9LZpXA2xVDhuPnSOZd.VURVkz7wgOLY3pnO0s7u2S1ZO32y', 'score': 1.0}
{'name': 'Jaime Lannister', 'password': '$2b$12$6vz7wiwO.EI5Rilvq1zUc./9480gb1uPtXcahDxIadgyC3PS8XCUK', 'score': 1.0}
{'name': 'Catelyn Stark', 'password': '$2b$12$fiaTH5Sh1zKNFX2i/FTEreWGjxoJxvmV7XL.qlfqCr8CwOxK.mZWS', 'score': 1.0}

Atlas Search 返回 password 值不是 null 的文档。结果中列出的第一个文档具有较高分数,因为 constant 选项会更改缺少 password 字段的文档的分数。

后退

搜索用户界面

来年

对结果进行分页