【问题标题】:how to run mongodb native query with mongodb date function in spring-data-mongodb?如何在 spring-data-mongodb 中使用 mongodb 日期函数运行 mongodb 本机查询?
【发布时间】:2017-10-06 18:53:10
【问题描述】:

我想在 spring data mongodb 中执行以下原生查询:

db.runCommand({aggregate:"mycollection", pipeline :[{$match : {$and : 
[{"orderDate" : {$gte : ISODate("2016-07-25T10:33:04.196Z")}},
{"orderDate" : {$lte :ISODate("2018-07-25T10:33:04.196Z")
    }}


]}}, 
{ "$project" : { "orderType" : 1 ,"count" : 1 ,   
     "month" : { "$month" : [ "$orderDate"]}}},
    { "$group" : { "_id" : { "month" : "$month" , "orderType" : "$orderType"} ,
    "count" : { "$sum" : 1} }}], 
    cursor:{batchSize:1000}})

我尝试使用 mongoTemplate.executeCommand 它执行一个 json 字符串,请帮助...

问候

克里斯

【问题讨论】:

    标签: java spring mongodb spring-data-mongodb


    【解决方案1】:

    您可以使用mongoTemplate.executeCommand(DBObject dbObject) 变体。

    只需将日期更改为 Json 解析器支持的扩展 json 并构建命令。

    类似

    long date1 = Instant.parse("2016-07-25T10:33:04.196Z").toEpochMilli();
    long date2 = Instant.parse("2018-07-25T10:33:04.196Z").toEpochMilli();
    
    DBObject dbObject = new BasicDBObject(
        "aggregate", "mycollection").append(
        "pipeline", JSON.parse("[\n" +
            "  {\n" +
            "    \"$match\": {\n" +
            "      \"$and\": [\n" +
            "        {\n" +
            "          \"orderDate\": {\n" +
            "            \"$gte\": \""+ date1 +"\"\n" +
            "          }\n" +
            "        },\n" +
            "        {\n" +
            "          \"orderDate\": {\n" +
            "            \"$gte\": \""+ date2 +"\"\n" +
            "          }\n" +
            "        }\n" +
            "      ]\n" +
            "    }\n" +
            "  },\n" +
            "  {\n" +
            "    \"$project\": {\n" +
            "      \"orderType\": 1,\n" +
            "      \"count\": 1,\n" +
            "      \"month\": {\n" +
            "        \"$month\": [\n" +
            "          \"$orderDate\"\n" +
            "        ]\n" +
            "      }\n" +
            "    }\n" +
            "  },\n" +
            "  {\n" +
            "    \"$group\": {\n" +
            "      \"_id\": {\n" +
            "        \"month\": \"$month\",\n" +
            "        \"orderType\": \"$orderType\"\n" +
            "      },\n" +
            "      \"count\": {\n" +
            "        \"$sum\": 1\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
        "]")).append(
        "cursor", new BasicDBObject("batchSize", 1000)
    );
    
    mongoTemplate.executeCommand(dbObject)
    

    【讨论】:

    • 日期字段是 ISODate,您的 sn-p 不工作请帮忙
    • Isodate 是一种 shell/JavaScript 类型。您必须将日期转换为扩展类型才能被驱动程序识别。所以尝试按原样使用我的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-11-28
    • 2023-03-20
    • 2021-06-19
    • 2011-09-12
    • 2012-05-05
    • 1970-01-01
    • 2016-02-14
    • 2019-06-30
    相关资源
    最近更新 更多