对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

运行MongoDB搜索查询

在本指南中,您可以了解如何使用 Node.js 驱动程序在集合上运行 MongoDB Search 查询。MongoDB Search 使您能够对 MongoDB 上托管的集合执行全文搜索。MongoDB Search 索引指定了搜索行为以及要索引的字段。

The example in this guide uses the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.

本部分介绍如何创建聚合管道以对集合运行MongoDB搜索查询。在管道阶段的数组中,添加 $search 阶段以指定搜索条件。然后,调用 aggregate() 方法并将管道数组作为参数传递。

提示

要了解更多关于聚合操作的信息,请参阅聚合操作指南。

在运行MongoDB 搜索查询之前,您必须在集合上创建MongoDB 搜索索引。要学习如何以编程方式创建MongoDB搜索索引,请参阅索引指南中的MongoDB搜索和MongoDB Vector Search搜索索引部分。

此示例通过执行以下操作来运行MongoDB 搜索查询:

  • 创建一个 $search 阶段,指示驱动程序查询title字段包含单词 "Alabama" 的文档

  • 创建一个 $project 阶段,指示驱动程序在查询结果中包含 title 字段

  • 将管道阶段传递到 aggregate() 方法并打印结果

const pipeline = [
{
$search: {
index: "default", // Replace with your search index name
text: {
query: "Alabama",
path: "title"
}
}
},
{
$project: {
title: 1
}
}
];
const cursor = collection.aggregate(pipeline);
for await (const document of cursor) {
console.log(document);
}
{
_id: new ObjectId('...'),
title: 'Alabama Moon'
}
{
_id: new ObjectId('...'),
title: 'Crazy in Alabama'
}
{
_id: new ObjectId('...'),
title: 'Sweet Home Alabama'
}

提示

Node.js驱动程序MongoDB Search 示例

要查看使用 Node.js 驱动程序执行 Atlas 搜索查询的更多示例,请参阅 Atlas 文档中的 MongoDB 搜索教程

要学习有关MongoDB Search 的更多信息,请参阅Atlas文档中的MongoDB Search

要学习;了解有关 aggregate() 方法的详情,请参阅API文档。