我试图根据一个查询按日期对集合中的文档进行计数。以下是示例文档:
{
"_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,
}
答案 0 :(得分:2)
您可以使用聚合方法获得相似的输出,
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
}