duanshan1977 2019-02-02 02:48
浏览 174
已采纳

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

I have a Mongo collection where every document in the collection has a sources array property. Searches on this property can be a combination of exact matches and regex. For example, when using Mongo shell, the query below searches for documents with source='gas valves' OR 'hose' is contained in source item. This works just as I expect

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

Things get a little trickier in mgo. Because some items in the $in array can be regex, and the others strings - the only way I have figured to make a query is by using $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}},
}

Is there some way I could construct one slice with both regex and string to use with $in - eliminating the need for the $or

  • 写回答

1条回答 默认 最新

  • dongxinyue2817 2019-02-02 03:10
    关注

    Use []interface{}:

    matches := []interface{}{
        bson.RegEx{"jo.+", "i"},
        "David",
        "Jenna",
    }
    
    db.C("people").Find(bson.M{"name": bson.M{"$in": matches}})
    

    [] means slice and interface{} means any type. Put together, []interface{} is a slice of any type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 github符合条件20分钟秒到账,github空投 提供github账号可兑换💰感兴趣的可以找我交流一下
  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?