$meta (aggregation)

Definition

  • $meta

New in version 2.6.

Returns the metadata associated with a document in a pipelineoperations, e.g. "textScore" when performing text search.

A $meta expression has the following syntax:

  1. { $meta: <metaDataKeyword> }

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

KeywordDescriptionSort Order"textScore"Returns the score associated with the corresponding$text query for each matching document. The text scoresignifies how well the document matched the search term orterms. If not used inconjunction with a $text query, returns a score ofnull.Descending

MongoDB Atlas Full-Text Search providesadditional $meta keywords, such as:

Behavior

The { $meta: "textScore" } expression is the only expression that the $sort stage accepts.

Although available for use everywhere expressions are accepted in thepipeline, the { $meta: "textScore" } expression is only meaningfulin 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:

  1. { "_id" : 1, "title" : "cakes and ale" }
  2. { "_id" : 2, "title" : "more cakes" }
  3. { "_id" : 3, "title" : "bread" }
  4. { "_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:

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

The operation returns the following results:

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

For more examples, see Text Search in the Aggregation Pipeline.