构建包含字符串和正则表达式模式的 $in 数组

Building $in array containing both strings and regex patterns

我有一个 Mongo 集合,集合中的每个文档都有一个来源数组 属性。对此 属性 的搜索可以是精确匹配和正则表达式的组合。例如,当使用 Mongo shell 时,下面的查询搜索源项中包含 source='gas valves' 或 'hose' 的文档。这正如我所料

db.notice.find({sources:{$in:[/\bhose/i,'gas valves']}})

mgo 中的事情变得有点棘手。因为 $in 数组中的某些项目可以是正则表达式,而其他项目是字符串 - 我想进行查询的唯一方法是使用 $or:

var regEx []bson.RegEx
var matches []string
// do stuff to populate regEx and matches
filter["$or"] = []bson.M{
    {"sources":bson.M{"$in":regEx}},
    {"sources":bson.M{"$in":matches}},
}

有什么方法可以构造一个包含正则表达式和字符串的切片以与 $in 一起使用 - 消除对 $or

的需要

使用[]interface{}:

matches := []interface{}{
    bson.RegEx{"jo.+", "i"},
    "David",
    "Jenna",
}

db.C("people").Find(bson.M{"name": bson.M{"$in": matches}})

[]表示切片,interface{}表示任意类型。放在一起,[]interface{} 是任何类型的切片。