Docs 菜单
Docs 主页
/ /

将视图与MongoDB Search 结合使用

您可以在 视图 上创建MongoDB搜索索引来转换文档和集合,以便对集合进行部分索引、支持不兼容的数据类型或数据模型等。

以下示例使用了 sample_mflixsample_airbnb 示例数据库。


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


注意

消歧

本页讨论标准视图。要了解按需物化视图,请参阅按需物化视图。

要了解视图类型之间的差异,请参阅与按需物化视图的比较。

您必须使用 MongoDB 8.0 或更高版本。

要编辑视图,您必须拥有用户管理员角色,并使用 collMod 数据库命令。

  • MongoDB Search 支持具有以下阶段的视图:

  • 索引名称在源集合及其所有视图中必须是唯一的。

  • MongoDB Search 不支持会生成动态结果的操作符的视图定义,例如$$USER_ROLES系统变量和$rand聚合操作符。

  • MongoDB Search 查询会返回源集合中出现的原始文档。

  • 要检索已转换的文档,请使用 storedSource 选项。

要创建视图,您必须拥有 createCollection 权限。

您可以对集合进行部分索引,以过滤文档。以下示例在 sample_mflix.movies 集合上创建一个视图,以便您可以仅搜索在 2000 年 1 月 1 日之后发行的电影。

1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2
use sample_mflix
3
db.createView(
"movies_ReleasedAfter2000",
"movies",
[
{
$match: {
$expr: {
$gt: [
"$released",
ISODate("2000-01-01")
]
}
}
}
]
)
4
  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

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

  3. 在侧边栏中,单击 Database 标题下的 Clusters

会显示集群页面。

5

您可以从 Search & Vector Search 选项或 Data Explorer 转到MongoDB搜索页面。

6
7

在页面上进行以下选择,然后单击 Next

Search Type

选择 MongoDB Search 索引类型。

Index Name and Data Source

指定以下信息:

  • Index Name: releasedAfter2000Index

  • Database and Collection:

    • sample_mflix

    • movies_ReleasedAfter2000

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.

重要提示:

默认下, MongoDB Search索引名为 default。如果保留此名称,则该索引将是任何未在运算符中指定其他 index 选项的MongoDB搜索查询的默认搜索索引。如果您要创建多个索引,我们建议您在所有索引之间保持一致的描述性命名约定。

8

Atlas 会显示一个 Toast(简短的非交互式通知),以通知索引正在构建中。

9

新创建的索引会出现在 Atlas Search 标签页上。在构建索引期间,Status 字段显示为 Build in Progress。索引构建完成后,Status 字段将显示为Active

重要提示:较大的集合需要较长的索引时间。索引构建完成后,您将收到电子邮件通知。

10

注意

以下示例通过对名为 movies_ReleasedAfter2000 的视图运行 .aggregate 命令来查询 releasedAfter2000Index 索引。如果您的集群正在运行 MongoDB v8.0,则必须使用视图上的索引查询源集合(例如,movies)。升级到 MongoDB v8.1+ 以直接查询视图。

use sample_mflix
db.movies_ReleasedAfter2000.aggregate([
{
$search: {
index: "releasedAfter2000Index",
text: {
path: "title",
query: "foo"
},
sort: {
released: 1
}
}
}
])
[
{
_id: ObjectId('573a13d2f29313caabd929f8'),
plot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo ...",
genres: [ 'Documentary', 'Music' ],
runtime: 150,
cast: [
'Shawn Cloninger',
'William Goldsmith',
'Jessy Greene',
'Dave Grohl'
],
num_mflix_comments: 0,
poster: 'https://m.media-amazon.com/images/M/MV5BMzE4OTczMTgxM15BMl5BanBnXkFtZTcwNTU1NjQxOA@@._V1_SY1000_SX677_AL_.jpg',
title: 'Foo Fighters: Back and Forth',
fullplot: `Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo tapes through the creation of their 2011 album, "Wasting Light."`,
languages: [ 'English' ],
released: ISODate('2011-04-05T00:00:00.000Z'),
directors: [ 'James Moll' ],
awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
lastupdated: '2015-08-19 00:00:25.937000000',
year: 2011,
imdb: { rating: 8.4, votes: 3745, id: 1853563 },
countries: [ 'USA' ],
type: 'movie',
tomatoes: {
viewer: { rating: 4.4, numReviews: 857, meter: 96 },
dvd: ISODate('2011-08-08T00:00:00.000Z'),
website: 'http://us.foofightersfilm.com/',
production: 'Cinedigm Digital Cinema',
lastUpdated: ISODate('2015-09-12T18:42:01.000Z')
}
}
]
1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2
use sample_mflix
3
db.createView(
"movies_ReleasedAfter2000",
"movies",
[
{
$match: {
$expr: {
$gt: [
"$released",
ISODate("2000-01-01")
]
}
}
}
]
)
4
db.movies_ReleasedAfter2000.createSearchIndex(
"releasedAfter2000Index",
{
"mappings": {
"dynamic": true
}
}
)
5

注意

以下示例通过对名为 movies_ReleasedAfter2000 的视图运行 .aggregate 命令来查询 releasedAfter2000Index 索引。如果您的集群正在运行 MongoDB v8.0,则必须使用视图上的索引查询源集合(例如,movies)。升级到 MongoDB v8.1+ 以直接查询视图。

use sample_mflix
db.movies_ReleasedAfter2000.aggregate([
{
$search: {
index: "releasedAfter2000Index",
text: {
path: "title",
query: "foo"
},
sort: {
released: 1
}
}
}
])
[
{
_id: ObjectId('573a13d2f29313caabd929f8'),
plot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo ...",
genres: [ 'Documentary', 'Music' ],
runtime: 150,
cast: [
'Shawn Cloninger',
'William Goldsmith',
'Jessy Greene',
'Dave Grohl'
],
num_mflix_comments: 0,
poster: 'https://m.media-amazon.com/images/M/MV5BMzE4OTczMTgxM15BMl5BanBnXkFtZTcwNTU1NjQxOA@@._V1_SY1000_SX677_AL_.jpg',
title: 'Foo Fighters: Back and Forth',
fullplot: `Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo tapes through the creation of their 2011 album, "Wasting Light."`,
languages: [ 'English' ],
released: ISODate('2011-04-05T00:00:00.000Z'),
directors: [ 'James Moll' ],
awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
lastupdated: '2015-08-19 00:00:25.937000000',
year: 2011,
imdb: { rating: 8.4, votes: 3745, id: 1853563 },
countries: [ 'USA' ],
type: 'movie',
tomatoes: {
viewer: { rating: 4.4, numReviews: 857, meter: 96 },
dvd: ISODate('2011-08-08T00:00:00.000Z'),
website: 'http://us.foofightersfilm.com/',
production: 'Cinedigm Digital Cinema',
lastUpdated: ISODate('2015-09-12T18:42:01.000Z')
}
}
]

以下示例允许您根据新的 totalPrice字段在 sample_airbnb.listingsAndReviews集合中搜索住宿,该字段是 pricecleaningFee 字段的总和。此外,由于MongoDB Search 不支持Decimal128 类型,因此我们将值转换为 Double

1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2
use sample_airbnb
3
db.createView(
"listingsAndReviews_totalPrice",
"listingsAndReviews",
[
{
$addFields: {
totalPrice: {
$add: [
{
$ifNull: [{ $toDouble: "$price" }, 0]
},
{
$ifNull: [{ $toDouble: "$cleaning_fee" }, 0]
}
]
}
}
}
]
)
4
  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

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

  3. 在侧边栏中,单击 Database 标题下的 Clusters

会显示集群页面。

5

您可以从 Search & Vector Search 选项或 Data Explorer 转到MongoDB搜索页面。

6
7

在页面上进行以下选择,然后单击 Next

Search Type

选择 MongoDB Search 索引类型。

Index Name and Data Source

指定以下信息:

  • Index Name: totalPriceIndex

  • Database and Collection:

    • sample_airbnb

    • listingsAndReviews_totalPrice

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.

重要提示:

默认下, MongoDB Search索引名为 default。如果保留此名称,则该索引将是任何未在运算符中指定其他 index 选项的MongoDB搜索查询的默认搜索索引。如果您要创建多个索引,我们建议您在所有索引之间保持一致的描述性命名约定。

8

Atlas 会显示一个 Toast(简短的非交互式通知),以通知索引正在构建中。

9

新创建的索引会出现在 Atlas Search 标签页上。在构建索引期间,Status 字段显示为 Build in Progress。索引构建完成后,Status 字段将显示为Active

重要提示:较大的集合需要较长的索引时间。索引构建完成后,您将收到电子邮件通知。

10

注意

以下示例通过对名为 listingsAndReviews_totalPrice 的视图运行 .aggregate 命令来查询 totalPriceIndex 索引。如果您的集群正在运行 MongoDB v8.0,则必须使用视图上的索引查询源集合(例如,listingsAndReviews)。升级到 MongoDB v8.1+ 以直接查询视图。

use sample_airbnb
db.listingsAndReviews_totalPrice.aggregate([
{
$search: {
index: "totalPriceIndex",
range: {
path: "totalPrice",
lte: 300
},
returnStoredSource: true
}
}
])
[
{ _id: '10006546', totalPrice: 115 },
{ _id: '1001265', totalPrice: 215 },
{ _id: '10021707', totalPrice: 40 },
{ _id: '1003530', totalPrice: 270 },
{ _id: '10038496', totalPrice: 269 },
{ _id: '10051164', totalPrice: 250 },
{ _id: '10057447', totalPrice: 50 },
{ _id: '10057826', totalPrice: 205 },
{ _id: '10059244', totalPrice: 43 },
{ _id: '10066928', totalPrice: 140 },
{ _id: '10082422', totalPrice: 60 },
{ _id: '10083468', totalPrice: 40 },
{ _id: '10084023', totalPrice: 231 },
{ _id: '10091713', totalPrice: 231 },
{ _id: '10092679', totalPrice: 58 },
{ _id: '10096773', totalPrice: 205 },
{ _id: '10112159', totalPrice: 90 },
{ _id: '10117617', totalPrice: 55 },
{ _id: '10120414', totalPrice: 150 },
{ _id: '10133554', totalPrice: 121 }
]
1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2
use sample_airbnb
3
db.createView(
"listingsAndReviews_totalPrice",
"listingsAndReviews",
[
{
$addFields: {
totalPrice: {
$add: [
{
$ifNull: [{ $toDouble: "$price" }, 0]
},
{
$ifNull: [{ $toDouble: "$cleaning_fee" }, 0]
}
]
}
}
}
]
)
4
db.listingsAndReviews_totalPrice.createSearchIndex(
"totalPriceIndex",
{
"mappings": {
"dynamic": true
},
"storedSource": {
"include": [
"totalPrice"
]
}
}
)
5

注意

以下示例通过对名为 listingsAndReviews_totalPrice 的视图运行 .aggregate 命令来查询 totalPriceIndex 索引。如果您的集群正在运行 MongoDB v8.0,则必须使用视图上的索引查询源集合(例如,listingsAndReviews)。升级到 MongoDB v8.1+ 以直接查询视图。

use sample_airbnb
db.listingsAndReviews_totalPrice.aggregate([
{
$search: {
index: "totalPriceIndex",
range: {
path: "totalPrice",
lte: 300
},
returnStoredSource: true
}
}
])
[
{ _id: '10006546', totalPrice: 115 },
{ _id: '1001265', totalPrice: 215 },
{ _id: '10021707', totalPrice: 40 },
{ _id: '1003530', totalPrice: 270 },
{ _id: '10038496', totalPrice: 269 },
{ _id: '10051164', totalPrice: 250 },
{ _id: '10057447', totalPrice: 50 },
{ _id: '10057826', totalPrice: 205 },
{ _id: '10059244', totalPrice: 43 },
{ _id: '10066928', totalPrice: 140 },
{ _id: '10082422', totalPrice: 60 },
{ _id: '10083468', totalPrice: 40 },
{ _id: '10084023', totalPrice: 231 },
{ _id: '10091713', totalPrice: 231 },
{ _id: '10092679', totalPrice: 58 },
{ _id: '10096773', totalPrice: 205 },
{ _id: '10112159', totalPrice: 90 },
{ _id: '10117617', totalPrice: 55 },
{ _id: '10120414', totalPrice: 150 },
{ _id: '10133554', totalPrice: 121 }
]

以下示例更新了 2000 年之前电影的 movies_ReleasedAfter2000 MongoDB 视图。

db.runCommand(
{
collMod: "movies_ReleasedAfter2000",
viewOn: "movies",
"pipeline": [
{
$match: {
$expr: {
$lt: [
"$released",
ISODate("2000-01-01T00")
]
}
}
}
]
}
)

运行此命令后, MongoDB Search 会自动检测视图定义中的更改,并在不停机的情况下执行重建索引。

以下示例返回 movies_ReleasedAfter2000 视图中的管道。

db.getCollectionInfos({ name: "movies_ReleasedAfter2000" })[0].options.pipeline
[
{
'$match': {
'$expr': { '$gt': [ '$released', ISODate('2000-01-01T00:00:00.000Z') ] }
}
}
]

当Atlas读取视图以过滤和转换源集合时,高度复杂的视图转换可能会导致性能下降。在这种情况下,请考虑创建物化视图以避免对Atlas造成额外的复制负载。为避免视图转换导致的查询延迟,可以直接查询源集合以检索原始文档。

在以下场景中,索引会更改为 FAILED 状态:

  • 您在与MongoDB搜索不兼容的视图上创建的索引。

  • 您编辑视图的方式不符合MongoDB搜索兼容性要求。

  • 您删除或更改视图的源集合。

    例如,如果一个视图是在另一个视图上创建的,并且将父视图源更改为另一个集合。

    注意

    如果一个视图是其他视图的后代,这一限制也同样适用。例如,您无法更改或移除所有后代所源自的源集合。

在以下场景中,索引会更改为 STALE 状态:

警告

如果在视图中定义的聚合管道与集合中的文档不兼容,搜索复制将失败。例如,如果 $toDouble 表达式对包含数组的文档字段进行操作,复制将失败。确保您的视图在处理集合中的所有文档时不会出错。

  • 如果视图定义导致聚合失败,而索引为 READY,则索引变为 STALE。解析文档或更改视图定义以使其不再失败后,索引将返回到 READY。当为 STALE 时,索引仍然可查询。如果索引脱离oplog,则会触发索引重建。

  • 如果视图定义在索引为 BUILDING 时导致聚合管道失败,则在修复文档之前,则索引生成将停滞。在您解析文档或更改视图定义后,索引将返回到 READY,以确保不再失败。

您可以在 Atlas 用户界面的索引状态详情页面查看索引状态。

当您使用 8.1 之前的MongoDB版本查询视图时,会出现此错误。

  • 如果您使用 8.0 之前的MongoDB版本,我们建议您升级到 8.1+ 以直接查询视图。您可以升级到 8.0 来查询源集合。

  • 如果使用MongoDB 8.0,则必须针对源集合查询视图索引。示例,对集合而不是视图运行.aggregate()

当您在视图上创建MongoDB搜索索引时,mongot进程执行的任务与您在常规集合上创建MongoDB搜索索引时相同。mongot进程:

  1. 根据集合索引定义中的规则创建MongoDB Search 索引。

  2. 监控变更流以了解您定义了MongoDB Search 索引的集合的文档和索引的当前状态。

  3. 处理MongoDB搜索查询,并将匹配文档的文档ID 和其他搜索元数据返回给 mongod,后者执行完整文档查找并将结果返回给客户端。

当您在视图上创建MongoDB搜索索引时,会在步骤 1 和 2 期间应用视图定义,并且转换后的文档会根据搜索索引定义进行索引,然后存储在磁盘上。

要了解有关视图的更多信息,请参阅视图。

要在视图上创建MongoDB Vector Search索引,请参阅将视图与MongoDB Vector Search结合使用。

后退

多个集合

在此页面上