On this page
$meta (aggregation)
On this page
Definition
$meta-
New in version 2.6.
Returns the metadata associated with a document in a pipeline operations, e.g.
"textScore"when performing text search.A
$metaexpression has the following syntax:{ $meta: <metaDataKeyword> }The
$metaexpression can specify the following keyword as the<metaDataKeyword>:Keyword Description Sort Order "textScore"Returns the score associated with the corresponding $textquery for each matching document. The text score signifies how well the document matched the search term or terms. If not used in conjunction with a$textquery, returns a score of null.Descending
Behavior
The { $meta: "textScore" } expression is the only expression that the $sort stage accepts.
Although available for use everywhere expressions are accepted in the pipeline, the { $meta: "textScore" } expression is only meaningful in a pipeline that includes a $match stage with a $text query.
Views do not support text search.
Examples
Consider an articles collection with the following documents:
{ "_id" : 1, "title" : "cakes and ale" }
{ "_id" : 2, "title" : "more cakes" }
{ "_id" : 3, "title" : "bread" }
{ "_id" : 4, "title" : "some cakes" }
The following aggregation operation performs a text search and use the $meta operator to group by the text search score:
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" : 1, "count" : 2 }
For more examples, see Text Search in the Aggregation Pipeline.