Control Search Results with Weights

Text search assigns a score to each document that contains the searchterm in the indexed fields. The score determines the relevance of adocument to a given search query.

For a text index, the weight of an indexed field denotes thesignificance of the field relative to the other indexed fields in termsof the text search score.

For each indexed field in the document, MongoDB multiplies the numberof matches by the weight and sums the results. Using this sum, MongoDBthen calculates the score for the document. See $metaoperator for details on returning and sorting by text scores.

The default weight is 1 for the indexed fields. To adjust the weightsfor the indexed fields, include the weights option in thedb.collection.createIndex() method.

Warning

Choose the weights carefully in order to prevent the need to reindex.

A collection blog has the following documents:

  1. {
  2. _id: 1,
  3. content: "This morning I had a cup of coffee.",
  4. about: "beverage",
  5. keywords: [ "coffee" ]
  6. }
  7.  
  8. {
  9. _id: 2,
  10. content: "Who doesn't like cake?",
  11. about: "food",
  12. keywords: [ "cake", "food", "dessert" ]
  13. }

To create a text index with different field weights for thecontent field and the keywords field, include the weightsoption to the createIndex() method. Forexample, the following command creates an index on three fields andassigns weights to two of the fields:

  1. db.blog.createIndex(
  2. {
  3. content: "text",
  4. keywords: "text",
  5. about: "text"
  6. },
  7. {
  8. weights: {
  9. content: 10,
  10. keywords: 5
  11. },
  12. name: "TextIndex"
  13. }
  14. )

The text index has the following fields and weights:

  • content has a weight of 10,
  • keywords has a weight of 5, and
  • about has the default weight of 1.

These weights denote the relative significance of the indexed fields toeach other. For instance, a term match in the content field has:

  • 2 times (i.e. 10:5) the impact as a term match in thekeywords field and
  • 10 times (i.e. 10:1) the impact as a term match in theabout field.