douxi0098 2018-03-14 22:39
浏览 102
已采纳

mgo $ all使用数组查询数组并且不区分大小写?

I have an array of ingredient names that is dynamic and provided per user. I'd like to match it to mongo documents where there is an array of objects called ingredients which has a property name. I've written a query (see below) which will take query parameters from the URL and will return all the documents that have all matching ingredient names, however this search is case sensitive and I'd like it not to be.

I've considered using bson.RegEx with Option: "i", however I'm not sure how to form this query or apply it to an array of strings.

Here is the case sensitive query:

// Check for ingredients, return all recipes that can be made using supplied ingredients
if qryPrms["ingredients"] != nil {
    mongodQ["ingredients.name"] = bson.M{"$all": qryPrms["ingredients"]}
}

mongodQ is the bson.M I use to query the collection later in the code. Ideally I could apply RegEx to each element in qryPrms["ingredients"] so it would return closely matching ingredients like cheese would return swiss cheese as well. This is also a more general mongodb question I suppose when it comes to querying with a dynamic array.

  • 写回答

1条回答 默认 最新

  • dtqi87613 2018-03-14 23:33
    关注

    I was able to accomplish this using a for loop to build a slice of type bson.RegEx.

    if qryPrms["ingredients"] != nil {
            var ingRegEx []bson.RegEx
            for i := range qryPrms["ingredients"] {
                ingRegEx = append(ingRegEx, bson.RegEx{Pattern: qryPrms["ingredients"][i], Options: "i"})
            }
            mongodQ["ingredients.name"] = bson.M{"$all": ingRegEx}
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置