mongodb - 如何在mongodb中使用查询和分组
问题描述
我试图根据一个查询按日期对集合中的文档进行计数。以下是示例文档:
{
"_id" : ObjectId("5d2b5c4a33ad6154e776658b"),
"_class" : "com.abc.mongo.docs.OCSMongoLog",
"jsonObject" : {
"keyIdentifier" : "218XXXXXXX25",
"microOperationName" : "Deduct amount from user balance.",
"moduleName" : "OCS",
"responseRaw" : "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schema
s.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema
-instance\"><soapenv:Body><AcceptDebbitUnitResponse xmlns=\"http://abc.xyz.ws.bss.ijk.google.com\"><AcceptUnitResp>
<ConversationID>101XXVVXX2111-testing</ConversationID><TransactionID>560XXCC273</TransactionID>
<Amount>1</Amount></AcceptUnitResp></AcceptDebbitUnitResponse></soapenv:Body></soapenv:Envelope>",
"operationName" : "Direct Debit",
"id" : null,
"createDate" : "2019-07-14 12:46:59.456",
"requestRaw" : "DebitBalance [conversationId=1012ZXXXXZZ916, transactionId=, originatingAddress=21894
7XXZZX25, destinationAddress=218XXXZZZ5, chargingAddress=21XXXZZZ25, amount=1]"
}
}
我正在尝试什么
我想根据包含字符的分组createDate
来计算文档的数量jsonObject.responseRaw
<Amount>
我尝试了以下查询:
db.oCSMongoLog.find( { $query: {"jsonObject.responseRaw" : {$regex : "<Amount>"}}}, $group: { "jsonObject.createDate" :
-1 } } ).count();
我在此遇到语法错误..任何人都可以帮助我解决这种情况。
我期待什么
就像是:
{
"2019-07-14" : count,
"2019-07-15" : count,
"2019-07-16" : count,
"2019-07-17" : count,
}
解决方案
您可以使用聚合方法来获得类似的输出,
db.oCSMongoLog.aggregate([
{
$match: {
"jsonObject.responseRaw": { $regex: "<Amount>" }
}
}, {
$group: {
_id: { $dateToString: { format: "%Y-%m-%d", date: "$jsonObject.createDate" } },
count: { $sum: 1 }
}
}])
输出:
/* 1 */
{
"_id" : "2019-07-14",
"count" : 1
},
/* 2 */
{
"_id" : "2019-07-15",
"count" : 1
},
/* 3 */
{
"_id" : "2019-07-26",
"count" : 2
}
推荐阅读
- python-3.x - Kivy Button 意外更改值 (size_hint)
- python - 没有名为“django_python3_ldap”的模块
- asp.net-mvc-4 - 在 IIS 应用程序中托管 MVC 4 应用程序
- r - R diff() 处理不适用
- spring-boot - 如何使用@RabbitListener 停止和重新启动来自 RabbitMQ 的消费消息
- php - php。卷曲错误
- html - 如何在移动视图中的特定位置将两个不同的列定位在一行中?
- linux - 在 sed bash 中写一个特殊字符
- json - JSON Schema Draft-07 if-then-else 必填字段验证似乎不正确
- css - 弯曲收缩不能垂直工作