mongodb - 使用正则表达式的 Mongo 聚合查询组
问题描述
我正在尝试编写一个脚本并从年份和特定月份添加的集合中获取数据。
并获取“名称”字段与我给定的正则表达式匹配的记录。
是否可以聚合使用正则表达式组?像这样的东西:
collection1.aggregate([
{"$match": {"$expr":{"$and":[{"$eq":[{"$year":"$updated_time"}, year]}, {"$eq":[{"$month":"$updated_time"}, month]}]}}},
{$group : {_id : {"Name": {"$regex": '^ABC', "$options": "i"} },count: { $sum: 1 }}
}]
或者哪个是获得它的最佳方式?如何修改此查询以获取该时间范围内的正则表达式匹配计数
解决方案
您可以$regex
在$match
自身内部使用,然后用于$count
获取匹配文档的数量
collection1.aggregate([
{ "$match": {
"$expr": {
"$and": [
{ "$eq": [{ "$year": "$updated_time" }, year] },
{ "$eq": [{ "$month": "$updated_time" }, month] }
]
},
"Name": { "$regex": "^ABC", "$options": "i" }
}},
{ "$count": "count" }
])
或者也$group
可以
collection1.aggregate([
{ "$match": {
"$expr": {
"$and": [
{ "$eq": [{ "$year": "$updated_time" }, year] },
{ "$eq": [{ "$month": "$updated_time" }, month] }
]
},
"Name": { "$regex": "^ABC", "$options": "i" }
}},
{ "$group": {
"_id": null,
"count": { "$sum": 1 }
}}
])
推荐阅读
- gnupg - gpg --list-keys 显示为 keyId 有序列表?
- css - 如何为价格标签制作直平行四边形CSS
- c# - 按位和运算符
- javascript - 如何使用javascript更改元素的类名
- html - 边界未到达边缘
- python - 在 plotly 中用下拉菜单绘制两个数据集
- javascript - 在 amp 页面中,是否可以包含在 window.onload 之后执行代码的 .js 文件?
- python - 在python中从单精度转换时将双精度设置为零
- macos - 如何允许通过终端发送 kystrokes?
- mysql - OpenJPA - 如何制定工作策略=针对 Oracle 的序列和策略=针对 MySql 的身份