$text - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$text

$text运算符用于对文档集合中的文本索引字段执行全文搜索。此运算符允许您搜索包含特定单词或短语的文档,并且可以与其他查询运算符结合使用以根据其他条件筛选结果。

参数

  • $search:要搜索的文本字符串。

示例(MongoDB 外壳)

以下示例演示如何使用$text运算符搜索包含 “兴趣” 一词的文档,并根据 “star_rating” 字段筛选结果。

创建示例文档

db.test.insertMany([ { "_id": 1, "star_rating": 4, "comments": "apple is red" }, { "_id": 2, "star_rating": 5, "comments": "pie is delicious" }, { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" }, { "_id": 4, "star_rating": 2, "comments": "bake the apple pie in the oven" }, { "_id": 5, "star_rating": 5, "comments": "interesting couch" }, { "_id": 6, "star_rating": 5, "comments": "interested in couch for sale, year 2022" } ]);

创建文本索引

db.test.createIndex({ comments: "text" });

查询示例

db.test.find({$and: [{star_rating: 5}, {$text: {$search: "interest"}}]})

输出

{ "_id" : 5, "star_rating" : 5, "comments" : "interesting couch" } { "_id" : 6, "star_rating" : 5, "comments" : "interested in couch for sale, year 2022" }

上面的命令返回的文档的文本索引字段包含任何形式的 “兴趣”,“star_rating” 等于 5。

代码示例

要查看使用该$text命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function searchDocuments() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('test'); const result = await collection.find({ $and: [ { star_rating: 5 }, { $text: { $search: 'interest' } } ] }).toArray(); console.log(result); client.close(); } searchDocuments();
Python
from pymongo import MongoClient def search_documents(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db.test result = list(collection.find({ '$and': [ {'star_rating': 5}, {'$text': {'$search': 'interest'}} ] })) print(result) client.close() search_documents()