Database Manual / Reference / Query Language / Expressions

$meta (expression operator)(表达式运算符)

Definition定义

$meta

Returns the metadata associated with a document, e.g. "textScore" when performing text search.返回与文档关联的元数据,例如执行文本搜索时的"textScore"

A $meta expression has the following syntax:$meta表达式具有以下语法:

{ $meta: <metaDataKeyword> }

The $meta expression can specify the following values as the <metaDataKeyword>:$meta表达式可以指定以下值作为<metaDataKeyword>

Keyword关键词Description描述
"textScore"

Returns the score associated with the corresponding $text query for each matching document. 返回与每个匹配文档的对应$text查询关联的分数。The text score signifies how well the document matched the search term or terms.文本得分表示文档与搜索词的匹配程度。

{ $meta: "textScore" } must be used in conjunction with a $text query.必须与$text查询结合使用。

In earlier versions, if not used in conjunction with a $text query, returns a score of null.在早期版本中,如果不与$text查询结合使用,则返回空分数。

$text provides text query capabilities for self-managed (non-Atlas) deployments. For data hosted on MongoDB, MongoDB also offers an improved full-text query solution, MongoDB Search.$text为自我管理(非Atlas)部署提供文本查询功能。对于托管在MongoDB上的数据,MongoDB还提供了改进的全文查询解决方案MongoDB搜索

"indexKey"Returns an index key for the document if a non-text index is used. The { $meta: "indexKey" } expression is for debugging purposes only, and not for application logic, and is preferred over cursor.returnKey().如果使用非文本索引,则返回文档的索引键。{ $meta: "indexKey" }表达式仅用于调试目的,不用于应用程序逻辑,并且优于cursor.returnKey()

MongoDB Search provides additional $meta keywords, such as:提供额外的$meta键,例如:

Refer to the MongoDB Search documentation for details.有关详细信息,请参阅MongoDB搜索文档。

Important

The following $meta keywords are not supported in Stable API V1:以下$meta键在Stable API V1中不受支持:

  • "textScore"
  • "indexKey"
  • "searchScore"
  • "searchHighlights"
  • "searchSequenceToken"
  • "searchScoreDetails"
  • "vectorSearchScore"

Behavior行为

Text Score Metadata 文本分数元数据$meta: "textScore"

Requires $text Search需要$text搜索

  • The { $meta: "textScore" } expression must be used in conjunction with $text. For example:{ $meta: "textScore" }表达式必须与$text结合使用。例如:

    • In aggregation, you must specify a $match stage with a $text query in the pipeline to use the { $meta: "textScore" } expression in later stage(s). If you do not specify the $text query in the $match stage, the operation fails.在聚合中,您必须在管道中使用$text查询指定一个$match阶段,以便在后续阶段使用{ $meta: "textScore" }表达式。如果不在$match阶段指定$text查询,则操作失败。

    • In find, you must specify the $text operator in the query predicate to use { $meta: "textScore" }. If you do not specify the $text operator in the query predicate, the operation fails.在查找中,必须在查询谓词中指定$text运算符才能使用{ $meta: "textScore" }。如果不在查询谓词中指定$text运算符,则操作将失败。

    Note

    $text provides text query capabilities for self-managed (non-Atlas) deployments. For data hosted on MongoDB, MongoDB also offers an improved full-text query solution, MongoDB Search.$text为自我管理(非Atlas)部署提供文本查询功能。对于托管在MongoDB上的数据,MongoDB还提供了改进的全文查询解决方案MongoDB搜索

Availability可用性

  • In aggregation, the { $meta: "textScore" } expression can be included in various stages that accept aggregation expressions, such as $project, $group $sort, etc.在聚合中,{ $meta: "textScore" }表达式可以包含在接受聚合表达式的各个阶段中,如$project$group$sort等。
  • In find, the { $meta: "textScore" } expression can be included in projection and in sort().在查找中,{ $meta: "textScore" }表达式可以包含在投影sort()中。

Usage In Projection投影中的使用

  • The { $meta: "textScore" } expression can be a part of the projection document to include the text score metadata.{ $meta: "textScore" }表达式可以是投影文档的一部分,以包含文本分数元数据。
  • The $meta expression can be present in either an inclusion or an exclusion projection.$meta表达式可以存在于包含或排除投影中。
  • If you set the expression to a field name that already exists in the document, the projected metadata value overwrites the existing value.如果将表达式设置为文档中已存在的字段名,则投影的元数据值将覆盖现有值。

Filter on Text Score文本分数筛选

  • In aggregation, following a stage that outputs a field with the text score value, you can specify a query condition or operate on the field in subsequent stages. For example, see $text in the Aggregation Pipeline on Self-Managed Deployments.在聚合中,在输出具有文本得分值的字段的阶段之后,您可以指定查询条件或在后续阶段对字段进行操作。例如,请参阅自我管理部署聚合管道中的$text
  • In find, you cannot specify a query condition on the text score. Use aggregation instead.在查找中,您不能对文本分数指定查询条件。请改用聚合。

Usage In Sort排序中的用法

  • The { $meta: "textScore" } expression can be used as a part of a sort operation to sort by the text score metadata; i.e.,{ $meta: "textScore" }表达式可以用作排序操作的一部分,按文本分数元数据进行排序;即。,

    • In aggregation, $sort stage.在聚合、$sort阶段。
    • In find, sort() method.在查找中,sort()方法中。
  • The "textScore" metadata sorts in descending order."textScore"元数据按降序排列。
  • To use in a sort operation, set the { $meta: "textScore" } expression to an arbitrary field name. The field name is disregarded by the query system.要在排序操作中使用,请将{ $meta: "textScore" }表达式设置为任意字段名。查询系统会忽略字段名。

Sort without Projection无投影排序

  • In aggregation, you can sort the resulting documents by { $meta: "textScore" } without also having to project the textScore.在聚合中,您可以按{ $meta: "textScore" }对生成的文档进行排序,而无需投影textScore

  • In find, you can sort the resulting documents by { $meta: "textScore" } without also having to project the textScore.在find中,您可以按{ $meta: "textScore" }对生成的文档进行排序,而无需投影textScore

Sort with Projection按投影排序

  • In aggregation, if you include the { $meta: "textScore" } expression in both the projection and sort, the projection and sort can have different field names for the expression. The field name in the sort is disregarded by the query system.在聚合中,如果在投影和排序中都包含{ $meta: "textScore" }表达式,则投影和排序可以为表达式使用不同的字段名。查询系统会忽略排序中的字段名。
  • In find, if you include the { $meta: "textScore" } expression in both the projection and sort, the projection and sort can have different field names for the expression. The field name in the sort is disregarded by the query system.在find中,如果在投影和排序中都包含{ $meta: "textScore" }表达式,则投影和排序可以为表达式使用不同的字段名。查询系统会忽略排序中的字段名。

Index Key Metadata $meta: "indexKey" (Aggregation and Find)索引键元数据$meta: "indexKey"(聚合和查找)

Usage用法

  • The { $meta: "indexKey" } expression is for debugging purposes only and not for application logic.{ $meta: "indexKey" }表达式仅用于调试目的,不用于应用程序逻辑。
  • The { $meta: "indexKey" } expression is preferred over cursor.returnKey().{ $meta: "indexKey" }表达式优于cursor.returnKey()

Availability可用性

  • In aggregation, the { $meta: "indexKey" } expression can be included in various stages that accept aggregation expressions, such as $project, $group $sortByCount, etc., but not $sort. However, with an aggregation pipeline, you can first project the { $meta: "indexKey" } expression (such as in a $project, $addFields, etc. ) and then, sort by that field in a subsequent $sort stage.在聚合中,{ $meta: "indexKey" }表达式可以包含在接受聚合表达式的各个阶段中,如$project$group$sortByCount等,但不能包含$sort。但是,使用聚合管道,您可以首先投影{ $meta: "indexKey" }表达式(例如在$project$addFields等中)。),然后在后续的$sort阶段按该字段排序。
  • In find, the { $meta: "indexKey" } expression is only available as part of the projection document.在查找中,{ $meta: "indexKey" }表达式仅作为投影文档的一部分可用。

Return Value返回值

  • The value returned depends on how the database decides to represent values in an index and may change across versions. The represented value may not be the actual value for the field.返回的值取决于数据库决定如何在索引中表示值,并且可能会在不同版本之间发生变化。表示的值可能不是字段的实际值。
  • The value returned depends on the execution plan chosen by the system. For example, if there are two possible indexes which can be used to answer the query, then the value of the "indexKey" metadata depends on which index is selected.返回的值取决于系统选择的执行计划。例如,如果有两个可能的索引可用于回答查询,则“indexKey”元数据的值取决于选择的索引。
  • If an index is not used, the { $meta: "indexKey" } expression does not return a value and the field is not included as part of the output.如果不使用索引,则{ $meta: "indexKey" }表达式不会返回值,并且该字段不会作为输出的一部分包含在内。

Examples示例

MongoDB Shell

$meta: "textScore"

Create an articles collection with the following documents:使用以下文档创建articles集合:

db.articles.insertMany([
{ "_id" : 1, "title" : "cakes and ale" },
{ "_id" : 2, "title" : "more cakes" },
{ "_id" : 3, "title" : "bread" },
{ "_id" : 4, "title" : "some cakes" },
{ "_id" : 5, "title" : "two cakes to go" },
{ "_id" : 6, "title" : "pie" }
])

Create a text index on the title field:title字段上创建文本索引

db.articles.createIndex( { title: "text"} )
Aggregation聚合

The following aggregation operation performs a text search and uses the $meta operator to group by the text search score:以下聚合操作执行文本搜索,并使用$meta运算符按文本搜索分数分组:

db.articles.aggregate(
[
{ $match: { $text: { $search: "cake" } } },
{ $group: { _id: { $meta: "textScore" }, count: { $sum: 1 } } }
]
)

The operation returns the following results:该操作返回以下结果:

{ "_id" : 0.75, "count" : 1 }
{ "_id" : 0.6666666666666666, "count" : 1 }
{ "_id" : 1, "count" : 2 }

For more examples, see $text in the Aggregation Pipeline on Self-Managed Deployments.有关更多示例,请参阅自我管理部署聚合管道中的$text

Find and Project查找和投影

The following query performs a text search for the term cake and uses the $meta operator in the projection document to include the score assigned to each matching document:以下查询对术语cake执行文本搜索,并在投影文档中使用$meta运算符来包含分配给每个匹配文档的分数:

db.articles.find(
{ $text: { $search: "cake" } },
{ score: { $meta: "textScore" } }
)

The operation returns the following documents with the text score:该操作返回以下具有文本分数的文档:

{ "_id" : 4, "title" : "some cakes", "score" : 1 }
{ "_id" : 1, "title" : "cakes and ale", "score" : 0.75 }
{ "_id" : 5, "title" : "two cakes to go", "score" : 0.6666666666666666 }
{ "_id" : 2, "title" : "more cakes", "score" : 1 }

For additional examples of "textScore" projections and sorts, see Relevance Score Examples.有关"textScore"预测和排序的其他示例,请参阅相关性得分示例

$meta: "indexKey"

Note

The { $meta: "indexKey" } expression is for debugging purposes only and not for application logic. MongoDB returns the value associated with the index chosen by the query system. { $meta: "indexKey" }表达式仅用于调试目的,不用于应用程序逻辑。MongoDB返回与查询系统选择的索引关联的值。The system can choose a different index upon subsequent execution.系统可以在后续执行时选择不同的索引。

For the selected index, the value returned depends on how the database decides to represent values in an index and may change across versions. The represented value may not be the actual value for the field.对于所选索引,返回的值取决于数据库决定如何表示索引中的值,并且可能会在不同版本之间发生变化。表示的值可能不是字段的实际值。

Create an orders collection with the following documents:使用以下文档创建orders集合:

db.orders.insertMany([
{ "item" : "abc", "price" : Decimal128("12"), "quantity" : 2, "type": "apparel" },
{ "item" : "jkl", "price" : Decimal128("20"), "quantity" : 1, "type": "electronics" },
{ "item" : "abc", "price" : Decimal128("10"), "quantity" : 5, "type": "apparel" }
])

Create the following compound index on the type and item fields:typeitem字段上创建以下复合索引:

db.orders.createIndex( { type: 1, item: 1 } )
Aggregation聚合

The following aggregation operation finds all documents with type equal to apparel and uses the $meta operator to include the index key value for the matching document if an index was used:以下聚合操作查找type等于apparel(服饰)的所有文档,并在使用索引的情况下使用$meta运算符包含匹配文档的索引键值:

db.orders.aggregate(
[
{ $match: { type: "apparel" } },
{ $addFields: { idxKey: { $meta: "indexKey" } } }
]
)
Find and Project查找和投影

The following operation finds all documents with type equal to apparel and uses the $meta operator to include the index key value for the matching document if an index was used:以下操作将查找type等于apparel(服饰)的所有文档,并在使用索引的情况下使用$meta运算符包含匹配文档的索引键值:

db.orders.find( { type: "apparel" }, { idxKey: { $meta: "indexKey" } } )

The operation returns the matching documents with their corresponding index key:该操作返回匹配的文档及其相应的索引键:

{
"_id" : ObjectId("5e98a33ceaf5e9dcf2b8dcde"),
"item" : "abc",
"price" : Decimal128("12"),
"quantity" : 2,
"type" : "apparel",
"idxKey" : { "type" : "apparel", "item" : "abc" }
}
{
"_id" : ObjectId("5e98a33ceaf5e9dcf2b8dce0"),
"item" : "abc",
"price" : Decimal128("10"),
"quantity" : 5,
"type" : "apparel",
"idxKey" : { "type" : "apparel", "item" : "abc" }
}

If no index is used, the { $meta: "indexKey" } does not return anything.如果不使用索引,则{ $meta: "indexKey" }不会返回任何内容。

Aggregation聚合

For example, the following operation does not use an index since no index exists on the price field to support the match condition:例如,以下操作不使用索引,因为price字段上不存在支持匹配条件的索引:

db.orders.aggregate(
[
{ $match: { price: { $gte: Decimal128("10") } } },
{ $addFields: { idxKey: { $meta: "indexKey" } } }
]
)
Find and Project查找和投影

For example, the following operation does not use an index since no index exists on the price field to support the match condition:例如,以下操作不使用索引,因为price字段上不存在支持匹配条件的索引:

db.orders.find(
{ price: { $gte: Decimal128("10") } },
{ idxKey: { $meta: "indexKey" } }
)

The operation returns the matching documents without the idxKey field:该操作返回不带idxKey字段的匹配文档:

{
"_id" : ObjectId("5e98a33ceaf5e9dcf2b8dcde"),
"item" : "abc",
"price" : NumberDecimal("12"),
"quantity" : 2,
"type" : "apparel"
}
{
"_id" : ObjectId("5e98a33ceaf5e9dcf2b8dcdf"),
"item" : "jkl",
"price" : NumberDecimal("20"),
"quantity" : 1,
"type" : "electronics"
}
{
"_id" : ObjectId("5e98a33ceaf5e9dcf2b8dce0"),
"item" : "abc",
"price" : NumberDecimal("10"),
"quantity" : 5,
"type" : "apparel"
}
C#

The C# examples on this page use the sample_mflix database from the Atlas sample datasets. 本页上的C#示例使用Atlas示例数据集中的sample_mflix数据库。To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started in the MongoDB .NET/C# Driver documentation.要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅MongoDB .NET/C#驱动程序文档中的入门

The following Movie class models the documents in the sample_mflix.movies collection:以下Movie类对sample_mflix.movies集合中的文档进行建模:

public class Movie
{
public ObjectId Id { get; set; }

public string Plot { get; set; }

public List<string> Genres { get; set; }

public int Runtime { get; set; }

public List<string> Cast { get; set; }

public string Title { get; set; }

[BsonElement("lastupdated")]
public DateTime LastUpdated { get; set; }

public string Rated { get; set; }

public int Year { get; set; }

public ImdbData Imdb { get; set; }

public string Type { get; set; }

public int Index { get; set; }

public string[] Comments { get; set; }

public List<BsonDocument> Highlights { get; set; }

public float Score { get; set; }

[BsonElement("scoreDetails")]
public SearchScoreDetails ScoreDetails { get; set; }

[BsonElement("searchScoreDetails")]
public SearchScoreDetails SearchScoreDetails { get; set; }

[BsonElement("paginationToken")]
public string PaginationToken { get; set; }

[BsonElement("plot_embedding")]
public float[] PlotEmbedding { get; set; }
}

Note

ConventionPack for Pascal Case

The C# classes on this page use Pascal case for their property names, but the field names in the MongoDB collection use camel case. To account for this difference, you can use the following code to register a ConventionPack when your application starts:

var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

To include the text search score by using the .NET/C# driver, call the MetaTextScore() method on the projection builder.

First, run the following code to create a text index on the Title field:

var indexModel = new CreateIndexModel<Movie>(
Builders<Movie>.IndexKeys.Text(m => m.Title));
movieCollection.Indexes.CreateOne(indexModel);

Then, add the following code to your application. The code performs a text search for the term "future" and uses the MetaTextScore() method to include the score assigned to each matching document. The code then sorts the results in descending order by their text score and returns the document with the highest score.

var filter = Builders<Movie>.Filter.Text("future");
var projection = Builders<Movie>.Projection
.Include(m => m.Title)
.Include(m => m.Plot)
.MetaTextScore(m => m.Score);

var result = movieCollection.Find(filter)
.Sort(Builders<Movie>.Sort.MetaTextScore("score"))
.Project(projection)
.FirstOrDefault();

The preceding operation returns the following document:上述操作返回以下文档:

{
"_id": {
"$oid": "573a1398f29313caabceb500"
},
"plot": "After visiting 2015, Marty McFly must repeat his visit to 1955 to
prevent disastrous changes to 1985... without interfering with his first trip.",
"title": "Back to the Future Part II",
"score": 1.59375
}