首页 > 解决方案 > 如何在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,
}

标签: mongodbmongodb-query

解决方案


您可以使用聚合方法来获得类似的输出,

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
}

推荐阅读