英文:
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" }
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论