douqian9729 2018-04-13 11:30
浏览 48
已采纳

将特定的退货查询转换为mgo

I have a query which returns all names from a collection's documents which contain a specific text. In the following example, return all names which contain the sequence "oh" case-insensitively; do not return other fields in the document:

find({name:/oh/i}, {name:1, _id:0})

I have tried to translate this query into mgo:

Find([]bson.M{bson.M{"name": "/oh/i"}, bson.M{"name": "1", "_id": "0"}})

but there are always zero results when using mgo. What is the correct syntax for such a query using mgo?

This question is different from the alleged duplicates because none of those questions deal with how to restrict MongoDB to return only a specific field instead of entire documents.

  • 写回答

1条回答 默认 最新

  • dongyun6835 2018-04-13 12:43
    关注

    To execute queries that use regexp patterns for filtering, use the bson.RegEx type.

    And to exclude fields from the result documents, use the Query.Select() method.

    Like in this example:

    c.Find(bson.M{"name": bson.RegEx{Pattern: "oh", Options: "i"}}).
        Select(bson.M{"name": 1, "_id": 0})
    

    Translation of the regexp:

    name:/oh/i
    

    This means to match documents where the name field has a value that contains the "oh" sub-string, case insensitive. This can be represented using a bson.RegEx, where the RegEx.Pattern field gets the pattern used in the above expression ("oh"). And the RegEx.Options may contain options now to apply / match the pattern. The doc lists the possible values. If the Options field contains the 'i' character, that means to match case insensitive.

    If you have a user-entered term such as "[a-c]", you have to quote regexp meta characters, so the final pattern you apply should be "\[a-c\]" To do that easily, use the regexp.QuoteMeta() function, e.g.

    fmt.Println(regexp.QuoteMeta("[a-c]")) // Prints: \[a-c\]
    

    Try it on the Go Playground.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看