我有一個 Mongo 集合,其中集合中的每個文檔都有一個 sources 數組屬性。對此屬性的搜索可以是精確匹配和正則表達式的組合。例如,當使用 Mongo shell 時,下面的查詢搜索源項中包含 source='gas valves' 或 'hose' 的文檔。這正如我所料db.notice.find({sources:{$in:[/\bhose/i,'gas valves']}})在 mgo 中事情變得有點棘手。因為 $in 數組中的某些項目可以是正則表達式,而其他項目是字符串 - 我想進行查詢的唯一方法是使用 $or:var regEx []bson.RegExvar matches []string// do stuff to populate regEx and matchesfilter["$or"] = []bson.M{ {"sources":bson.M{"$in":regEx}}, {"sources":bson.M{"$in":matches}},}有什么方法可以構建一個包含正則表達式和字符串的切片以與 $in 一起使用 - 消除對 $or 的需要
1 回答

呼如林
TA貢獻1798條經驗 獲得超3個贊
使用[]interface{}:
matches := []interface{}{
bson.RegEx{"jo.+", "i"},
"David",
"Jenna",
}
db.C("people").Find(bson.M{"name": bson.M{"$in": matches}})
[]表示切片,interface{}表示任何類型。放在一起,[]interface{}是任何類型的切片。
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報
0/150
提交
取消