首页 > 解决方案 > 如何使用 golang 和 mongo-go-driver 在 mongodb 中创建文本索引?

问题描述

我正在尝试对集合进行全文搜索,但为了做到这一点,我需要创建一个文本索引。如何在两个字段上创建文本索引?

我知道我必须使用这样的东西:

opts := options.CreateIndexes().SetMaxTime(10 * time.Second)

idxFiles := []mongo.IndexModel{
    {
      Keys: bsonx.Doc{{"name": "text"}},
    },
  }

db.Collection("mycollection").Indexes().CreateMany(context, idx, opts)

标签: mongodbgo

解决方案


我已经建立了解决方案:

    coll := db.Collection("test")
    index := []mongo.IndexModel{
        {
            Keys: bsonx.Doc{{Key: "name", Value: bsonx.String("text")}},
        },
        {
            Keys: bsonx.Doc{{Key: "createdAt", Value: bsonx.Int32(-1)}},
        },
    }

    opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
    _, errIndex = coll.Indexes().CreateMany(context, index, opts)
    if err != nil {
        panic(errIndex)
    }

推荐阅读