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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化