how to run mongodb native query with mongodb date function in spring-data-mongodb?

佐手、 提交于 2019-12-11 10:57:19

问题


I want to execute the below native query in 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}})

I tried with mongoTemplate.executeCommand it executes a json string, Please help...

Regards

Kris


回答1:


You can use the mongoTemplate.executeCommand(DBObject dbObject) variant.

Just change the date to extended json which is supported by Json parser and build the command.

Something like

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)


来源:https://stackoverflow.com/questions/46612203/how-to-run-mongodb-native-query-with-mongodb-date-function-in-spring-data-mongod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!