使用mongo-go-driver创建动态过滤器

时间:2019-06-26 15:44:30

标签: mongodb go mongo-go

我想用mongo-go-driver创建一个动态过滤器。

例如,我有以下文档:

{
"_id":"5d1231380a2a2b39a99c3ed1"},
"name":"flower.png",
"colors":["#ffffff","#212121","#999999","#dbdbdb","#ff5252"],
},
{
"_id":"5d1231380a2a2b39a99c3ed0"},
"name":"image of go.jpg",
"colors":["#dedede","#dfdfdf","#dddddd","#e0e0e0","#e2e2e2"],
},
{
"_id":"5d1231380a2a2b39a99c3ecf"},
"name":"bolket rulez.png",
"colors":["#000000","#010101","#020202","#030303","#040404"],
},
{
"_id":"5d1231380a2a2b39a99c3ecf"},
"name":"bolket photo.png",
"colors":["#ffffff","#010101","#020202","#030303","#040404"],
}

现在,我希望名称中带有“ bolket”和“ #ffffff”颜色的所有文档。

我尝试使用此过滤器:

filter := make(bson.D, 2)

    if f.Name != "" {
        filter = append(filter, bson.E{Key: "name", Value: bson.M{"$text": bson.M{"$search": f.Name}}})
    }

    if f.Color != "" {
        filter = append(filter, bson.E{Key: "colors", Value: bson.M{"$in": f.Color}})
    }

但是使用此过滤器,我会遇到以下错误:(BadValue) unknown operator: $text

如何创建动态过滤器?

1 个答案:

答案 0 :(得分:0)

查询op $text搜索文档中的文本索引字段,您无法使用$text

进行单个字段搜索

假设您已经在name上创建了文本索引,然后尝试:

  if f.Name != "" {
        filter = append(filter, bson.E{Key: "$text", Value: bson.M{"$search": f.Name}})
    }