$meta (aggregation)


New in version 2.6.

The $meta operator returns the metadata associated with a document in a pipeline operations, e.g. "textScore" when performing text search.

A $meta expression has the following syntax:

{ <projectedFieldName>: { $meta: <metaDataKeyword> } }

The $meta expression can specify the following keyword as the <metaDataKeyword>:

Keyword Description Sort Order
"textScore" Returns the score associated with the corresponding query:$text query for each matching document. The text score signifies how well the document matched the stemmed term or terms. If not used in conjunction with a query:$text query, returns a score of 0.0 Descending


The $meta expression can be a part of the $project stage and the $sort stage.

Projected Field Name

If the specified <projectedFieldName> already exists in the matching documents, in the result set, the existing fields will return with the $meta values instead of with the stored values.


The $meta expression can be used in the $project stage, as in:

     { $match: { $text: { $search: "cake" } } },
     { $project: { title: 1, score: { $meta: "textScore" } } }

The inclusion of the $meta aggregation expression in the $project pipeline specifies both the inclusion of the metadata as well as the exclusion of the fields, other than _id, that are not explicitly included in the projection document. This differs from the behavior of the $meta projection operator in a db.collection.find() operation which only signifies the inclusion of the metadata and does not signify an exclusion of other fields.


To use the metadata to sort, specify the $meta expression in $sort stage, as in:

     { $match: { $text: { $search: "cake tea" } } },
     { $sort: { score: { $meta: "textScore" } } },
     { $project: { title: 1, _id: 0 } }

The specified metadata determines the sort order. For example, the "textScore" metadata sorts in descending order.


For examples of "textScore" projections and sorts, see Text Search in the Aggregation Pipeline.