如何在使用MongoDb Aggregate时过滤搜索字符串

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

how to filter using MongoDb Aggregate when searching string

问题

我想在类型为String的文件fileName上进行搜索。

  1. {
  2. _id : ObjectId('645a42950d627800984c9f2d'),
  3. fileName, "untitled document (2).xlxs"
  4. },
  5. {
  6. _id : ObjectId('645a42950d627800984c9f2d'),
  7. fileName, "fileUpload.xlxs"
  8. },
  9. {
  10. _id : ObjectId('645a42950d627800984c9f2d'),
  11. fileName, "document (1).xlxs"
  12. }

这是我的示例数据。

Q1. 我想筛选出与我的关键词document匹配的数据。

预期解决方案:返回2个结果

Q2. 我想筛选出与untitled document (2).xlxs匹配的数据。

预期解决方案:返回1个结果

如何使用MongoDb聚合实现这个目标。

英文:

I want to search on the file fileName which is of type String.

  1. {
  2. _id : ObjectId('645a42950d627800984c9f2d'),
  3. fileName, "untitled document (2).xlxs"
  4. },
  5. {
  6. _id : ObjectId('645a42950d627800984c9f2d'),
  7. fileName, "fileUpload.xlxs"
  8. },
  9. {
  10. _id : ObjectId('645a42950d627800984c9f2d'),
  11. fileName, "document (1).xlxs"
  12. }

This is my example data.

Q1. I want to filter those data which matches my word document.

Expected Solution : To return 2 results

Q2. I want to filter those data which matches untitled document (2).xlxs.

Expected Solution : To return 1 results

How to achieve this using mongoDb aggregate.

答案1

得分: 0

Your approach is not bad, however you need $match rather than $addFields. And you mixed $regexMatch with $regex.
Would be this one:

  1. db.collection.aggregate([
  2. { $match: { fileName: { $regex: "document", $options: "s" } } }
  3. ])

or a bit shorter:

  1. db.collection.aggregate([
  2. { $match: { fileName: /document/s } }
  3. ])
  4. db.collection.find(
  5. { fileName: /document/s }
  6. )
  7. and for the second one:
  8. db.collection.aggregate([
  9. { $match: { fileName: "untitled document (2).xlxs" } }
  10. ])
  11. db.collection.find(
  12. { fileName: "untitled document (2).xlxs" }
  13. )
  14. [1]: https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/regexMatch/
  15. [2]: https://www.mongodb.com/docs/v6.0/reference/operator/query/regex/
英文:

Your approach is not bad, however you need $match rather than $addFields. And you mixed $regexMatch with $regex.
Would be this one:

  1. db.collection.aggregate([
  2. { $match: { fileName: { $regex: "document", $options: "s" } } }
  3. ])

or a bit shorter:

  1. db.collection.aggregate([
  2. { $match: { fileName: /document/s } }
  3. ])
  4. db.collection.find(
  5. { fileName: /document/s }
  6. )

and for the second one:

  1. db.collection.aggregate([
  2. { $match: { fileName: "untitled document (2).xlxs" } }
  3. ])
  4. db.collection.find(
  5. { fileName: "untitled document (2).xlxs" }
  6. )

huangapple
  • 本文由 发表于 2023年5月11日 19:37:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76227222.html
匿名

发表评论

匿名网友

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

确定