Docs 菜单
Docs 主页
/ / /
Node.js 驱动程序

运行 Atlas Search 查询

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

本指南中的示例使用来自 Atlas 示例数据集sample_mflix 数据库中的 movies 集合。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅Atlas 入门指南

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

提示

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

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

此示例通过执行以下操作来运行Atlas Search查询:

  • 创建一个 $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'
}

提示

节点.js 驱动程序 Atlas Search 示例

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

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

要了解有关 aggregate() 方法的更多信息,请参阅 API 文档。

后退

运行数据库命令

在此页面上