2

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 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

the date field is of ISODate, your snippet not working please help
Isodate is a shell/JavaScript type. You have to convert the date into extended type to be recognized by driver. So try using my answer as is.
and how to loop through the results

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.