You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为MongoDB多字段创建指定对应语言的文本索引?

Specifying Per-Field Languages for MongoDB Text Indexes

Great question! When dealing with fields in different languages (like your English content and Portuguese about fields), you can define language-specific settings directly in the text index creation command. This ensures MongoDB uses the correct stemming rules and stop words for each language, making your text searches more accurate.

Here's how to modify your existing index creation code to specify languages per field:

db.blog.createIndex(
  {
    content: { $type: "text", $default_language: "english" },
    keywords: "text", // Uses default database language (usually English unless configured otherwise)
    about: { $type: "text", $default_language: "portuguese" }
  },
  {
    weights: { content: 10, keywords: 5 },
    name: "TextIndex"
  }
);

Key Details:

  • For each field that needs a specific language, replace the simple "text" value with an object containing:
    • $type: "text": Marks the field as part of the text index
    • $default_language: Sets the language for that field (use MongoDB's supported language codes, e.g., "english", "portuguese", "spanish", etc.)
  • The keywords field in this example uses the default database language—you can override it with the same object syntax if it needs a different language
  • Weights and index name are preserved exactly as in your original example, so search relevance prioritization remains unchanged

This setup ensures that MongoDB indexes the content field using English-specific rules and the about field using Portuguese rules, which is ideal for multilingual collections!

内容的提问来源于stack exchange,提问作者Miguel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:20:12