使Mongo的聚合管道不区分大小写。

huangapple go评论130阅读模式
英文:

Making mongo's aggregation pipeline case insenstive

问题

我正在使用Mongo的聚合管道在一个集合上进行搜索。

这是我的过滤条件:

  1. filter := bson.D{
  2. {"$project", bson.D{
  3. {"names", bson.D{
  4. {"$filter", bson.D{
  5. {"input", "$names"},
  6. {"as", "names"},
  7. {"cond", bson.D{
  8. {"$and", bson.A{
  9. bson.D{{"$eq", bson.A{"$$names.firstname", "John"}}},
  10. bson.D{{"$eq", bson.A{"$$names.lastname", "Doe"}}},
  11. }},
  12. }},
  13. }},
  14. }},
  15. }},
  16. }

这个过滤器工作得很好,但它是区分大小写的。如果传入john而不是John,它将返回0个文档。如何使firstnamelastname不区分大小写?

英文:

I am using mongo's aggregation pipeline to do a search on a collection.

Here is my filter condition:

  1. filter := bson.D{
  2. {"$project", bson.D{
  3. {"names", bson.D{
  4. {"$filter", bson.D{
  5. {"input", "$names"},
  6. {"as", "names"},
  7. {"cond", bson.D{
  8. {"$and", bson.A{
  9. bson.D{{"$eq", bson.A{"$$names.firstname", "John"}}},
  10. bson.D{{"$eq", bson.A{"$$names.lastname", "Doe"}}},
  11. }},
  12. }},
  13. }},
  14. }},
  15. }},
  16. }

This filter works well but it is case sensitive. If pass john instead of John, it returns 0 documents. How do I make firstname and lastname case insenstive?

答案1

得分: 1

你可以在 $filter 中使用 $regexMatch,像这样:

请注意,我使用了正则表达式 ^name$ 来匹配单词,你可以使用你想要的正则表达式,但是使用选项 i 时,正则表达式是不区分大小写的。

  1. db.collection.aggregate([
  2. {
  3. "$project": {
  4. "names": {
  5. "$filter": {
  6. "input": "$names",
  7. "as": "names",
  8. "cond": {
  9. "$and": [
  10. {
  11. "$regexMatch": {
  12. "input": "$$names.firstname",
  13. "regex": "^John$",
  14. "options": "i"
  15. }
  16. },
  17. {
  18. "$regexMatch": {
  19. "input": "$$names.lastname",
  20. "regex": "^Doe$",
  21. "options": "i"
  22. }
  23. }
  24. ]
  25. }
  26. }
  27. }
  28. }
  29. }
  30. ])

示例可以在这里找到。

英文:

You can use $regexMatch into $filter like this:

Note that I've used Regex ^name$ to match only the word, you can use the regex you want, but with option i, the regex is case insensitive.

  1. db.collection.aggregate([
  2. {
  3. "$project": {
  4. "names": {
  5. "$filter": {
  6. "input": "$names",
  7. "as": "names",
  8. "cond": {
  9. "$and": [
  10. {
  11. "$regexMatch": {
  12. "input": "$$names.firstname",
  13. "regex": "^John$",
  14. "options": "i"
  15. }
  16. },
  17. {
  18. "$regexMatch": {
  19. "input": "$$names.lastname",
  20. "regex": "^Doe$",
  21. "options": "i"
  22. }
  23. }
  24. ]
  25. }
  26. }
  27. }
  28. }
  29. }
  30. ])

Example here

huangapple
  • 本文由 发表于 2021年8月24日 18:52:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/68906235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定