如何使用 Atlas Search 检查空值和非空值
本教程介绍如何使用 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
值的示例查询。
使用动态映射创建 Atlas Search 索引
在本节中,您将创建一个 Atlas Search 索引,该索引使用动态映射对 sample_mflix.users
集合中的所有可动态索引字段动态创建索引。
输入Index Name ,然后设置Database and Collection 。
在 Index Name 字段中输入
null-check-tutorial
。注意
如果将索引命名为
default
,则在使用 $search 管道阶段时,您无需指定index
参数。否则,您必须使用index
参数指定索引名称。在 Database and Collection(数据库和集合)部分中找到
sample_mflix
数据库,然后选择users
集合。
指定索引定义。
您可以创建使用动态映射或静态映射的 Atlas Search 索引。要了解有关动态和静态映射的更多信息,请参阅静态和动态映射。
以下索引定义对 movies
集合中的支持类型字段动态创建索引。您可以使用 Atlas Search Visual Editor 或 Atlas Search JSON Editor 在 Atlas 用户界面中创建索引。
可视化编辑器
单击 Next(连接)。
查看
movies
集合的"default"
索引定义。
JSON 编辑器
单击 Next(连接)。
查看索引定义。
索引定义应类似于以下内容:
{ "mappings": { "dynamic": true } } 上述索引定义对
movies
集合中每个文档中的支持类型字段动态创建索引。单击 Next(连接)。
检查null
值
➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。
设置 Atlas Search 索引后,可以连接到 Atlas 集群并对 sample_mflix.users
集合中的字段运行查询。以下查询使用复合和通配符操作符来查找所有具有 password
字段值为 null
的文档。
注意
我们不建议使用通配符操作符来查询索引大小较大的集合。 要了解更多信息并投票支持 Atlas Search 增强功能以支持空数据类型的索引和查询,请使用 MongoDB 反馈引擎。
使用复合运算符运行 Atlas Search 查询以搜索users
集合。
以下查询使用 $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
连接到mongosh
中的集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
使用sample_mflix
数据库。
在 mongosh
提示符下运行以下命令:
use sample_mflix
使用compound
和wildcard
操作符对users
集合运行 Atlas Search 查询。
以下查询使用 $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 }
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
使用compound
和wildcard
操作符对users
集合运行 Atlas Search 查询。
以下查询使用 $search
管道阶段查询该集合。该查询使用了以下复合运算符子句:
must
子句以仅查找具有password
字段的文档。mustNot
带有通配符操作符的子句,以排除在password
字段中具有任何值的所有文档。
若要在 MongoDB Compass 中运行此查询:
单击 Aggregations 标签页。
单击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 }
将Program.cs
文件的内容替换为以下代码。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用
$search
管道阶段查询该集合。该查询使用了以下复合运算符子句:must
子句以仅查找具有password
字段的文档。mustNot
带有通配符操作符的子句,以排除在password
字段中具有任何值的所有文档。
遍历游标以打印与查询匹配的文档。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public 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 [ ]39 public class UserDocument 40 { 41 [ ]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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
将以下代码复制并粘贴到isnull-query.go
文件中。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用
$search
管道阶段查询该集合。该查询使用了以下复合运算符子句:must
子句以仅查找具有password
字段的文档。mustNot
带有通配符操作符的子句,以排除在password
字段中具有任何值的所有文档。
遍历游标以打印与查询匹配的文档。
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 // 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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
将以下代码复制并粘贴到IsNullQuery.java
文件中。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用
$search
管道阶段查询该集合。该查询使用了以下复合运算符子句:must
子句以仅查找具有password
字段的文档。mustNot
带有通配符操作符的子句,以排除在password
字段中具有任何值的所有文档。
遍历游标以打印与查询匹配的文档。
1 import static com.mongodb.client.model.Aggregates.limit; 2 import static com.mongodb.client.model.Aggregates.project; 3 import static com.mongodb.client.model.Projections.excludeId; 4 import static com.mongodb.client.model.Projections.fields; 5 import static com.mongodb.client.model.Projections.include; 6 import com.mongodb.client.MongoClient; 7 import com.mongodb.client.MongoClients; 8 import com.mongodb.client.MongoCollection; 9 import com.mongodb.client.MongoDatabase; 10 import org.bson.Document; 11 import java.util.Arrays; 12 13 public 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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
将以下代码复制并粘贴到IsNullQuery.kt
文件中。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用
$search
管道阶段查询该集合。该查询使用了以下复合运算符子句:must
子句以仅查找具有password
字段的文档。mustNot
带有通配符操作符的子句,以排除在password
字段中具有任何值的所有文档。
遍历游标以打印与查询匹配的文档。
1 import com.mongodb.kotlin.client.coroutine.MongoClient 2 import kotlinx.coroutines.runBlocking 3 import org.bson.Document 4 5 fun 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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
将以下代码复制并粘贴到isnull-query.js
文件中。
此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的 Node.js 驱动程序。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用
$search
管道阶段查询该集合。该查询使用了以下复合运算符子句:must
子句以仅查找具有password
字段的文档。mustNot
带有通配符操作符的子句,以排除在password
字段中具有任何值的所有文档。
遍历游标以打印与查询匹配的文档。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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 } 46 run().catch(console.dir);
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
将以下代码复制并粘贴到isnull-query.py
文件中。
此代码示例将执行以下任务:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用DNS种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用
$search
管道阶段查询该集合。该查询使用了以下复合运算符子句:must
子句以仅查找具有password
字段的文档。mustNot
带有通配符操作符的子句,以排除在password
字段中具有任何值的所有文档。
遍历游标以打印与查询匹配的文档。
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [{ 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 27 result = client["sample_mflix"]["users"].aggregate(pipeline) 28 29 # print results 30 for i in result: 31 print(i)
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
Atlas Search 返回一个 password
值为 null
的文档。Atlas Search 不包含缺少 password
字段的文档,因为查询指定 password
字段必须存在。
查找所有非null
值
➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。
设置 Atlas Search 索引后,您可以连接到 Atlas 集群并对 sample_mflix.users
集合中的字段运行查询。以下查询使用复合运算符和通配符来查找在 password
字段中没有 null
值或没有 password
字段的文档。
使用复合运算符运行 Atlas Search 查询以搜索users
集合。
以下查询仅搜索在 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"
连接到mongosh
中的集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
使用sample_mflix
数据库。
在 mongosh
提示符下运行以下命令:
use sample_mflix
使用compound
和wildcard
操作符对users
集合运行 Atlas Search 查询。
以下查询仅搜索在 password
字段中没有 null
值的用户。查询包括以下管道阶段:
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 }
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
使用compound
和wildcard
操作符对users
集合运行 Atlas Search 查询。
查询使用了下列管道阶段:
若要在 MongoDB Compass 中运行此查询:
单击 Aggregations 标签页。
单击 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 }
将Program.cs
文件的内容替换为以下代码。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下管道阶段:
遍历游标以打印与查询匹配的文档。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public 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 [ ]49 public class UserDocument 50 { 51 [ ]52 public string Id { get; set; } 53 public string Name { get; set; } 54 [ ]55 public string Password { get; set; } 56 public double Score { get; set; } 57 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行以下命令以查询集合。
运行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 }
将以下代码复制并粘贴到notnull-query.go
文件中。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 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 // 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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行以下命令以查询集合。
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}]
将以下代码复制并粘贴到NotNullQuery.java
文件中。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下管道阶段:
遍历游标以打印与查询匹配的文档。
1 import static com.mongodb.client.model.Aggregates.limit; 2 import static com.mongodb.client.model.Aggregates.project; 3 import static com.mongodb.client.model.Projections.*; 4 import com.mongodb.client.MongoClient; 5 import com.mongodb.client.MongoClients; 6 import com.mongodb.client.MongoCollection; 7 import com.mongodb.client.MongoDatabase; 8 import org.bson.Document; 9 import java.util.Arrays; 10 11 public 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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
编译并运行NotNullQuery.java
文件。
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}
将以下代码复制并粘贴到NotNullQuery.kt
文件中。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下管道阶段:
遍历游标以打印与查询匹配的文档。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun 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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行NotNullQuery.kt
文件。
当你在 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}}
将以下代码复制并粘贴到notnull-query.js
文件中。
此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的 Node.js 驱动程序。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用以下管道阶段:
遍历游标以打印与查询匹配的文档。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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 } 59 run().catch(console.dir);
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行以下命令以查询集合。
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 }
将以下代码复制并粘贴到notnull.py
文件中。
此代码示例将执行以下任务:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用DNS种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用以下管道阶段:
遍历游标以打印与查询匹配的文档。
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [{ 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 49 result = client["sample_mflix"]["users"].aggregate(pipeline) 50 51 # print results 52 for i in result: 53 print(i)
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行以下命令以查询集合。
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
字段的文档的分数。