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

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

how to filter using MongoDb Aggregate when searching string

问题

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

{
 _id : ObjectId('645a42950d627800984c9f2d'),
 fileName, "untitled document (2).xlxs"
},
{
 _id : ObjectId('645a42950d627800984c9f2d'),
 fileName, "fileUpload.xlxs"
},
{
 _id : ObjectId('645a42950d627800984c9f2d'),
 fileName, "document (1).xlxs"
}

这是我的示例数据。

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

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

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

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

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

英文:

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


{
 _id : ObjectId('645a42950d627800984c9f2d'),
 fileName, "untitled document (2).xlxs"
},
{
 _id : ObjectId('645a42950d627800984c9f2d'),
 fileName, "fileUpload.xlxs"
},
{
 _id : ObjectId('645a42950d627800984c9f2d'),
 fileName, "document (1).xlxs"
}

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:

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

or a bit shorter:

db.collection.aggregate([
   { $match: { fileName: /document/s } }
])

db.collection.find(
   { fileName: /document/s }
)

and for the second one:

db.collection.aggregate([
   { $match: { fileName: "untitled document (2).xlxs" } }
])

db.collection.find(
   { fileName: "untitled document (2).xlxs" }
)

[1]: https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/regexMatch/
[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:

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

or a bit shorter:

db.collection.aggregate([
   { $match: { fileName: /document/s } }
])

db.collection.find(
   { fileName: /document/s }
)

and for the second one:

db.collection.aggregate([
   { $match: { fileName: "untitled document (2).xlxs" } }
])

db.collection.find(
   { fileName: "untitled document (2).xlxs" }
)

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:

确定