简体   繁体   中英

Creating a dynamic filter with mongo-go-driver

I want create a dynamic filter with the mongo-go-driver.

For example, I have this documents:

{
"_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"],
}

Now I want all documents that have "bolket" in the name and "#ffffff" color.

I have tryed with this filter:

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}})
    }

But with this filter I have this error: (BadValue) unknown operator: $text

How can I create a dynamic filter???

query op $text search across text index fields on a doc, you can't do single field search with $text

assuming you have created a text index on name , then try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM