如何在spring-data-mongodb中使用mongodb date函数运行mongodb本机查询? [英] how to run mongodb native query with mongodb date function in spring-data-mongodb?

查看:427
本文介绍了如何在spring-data-mongodb中使用mongodb date函数运行mongodb本机查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在spring数据mongodb中执行以下本机查询:

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}})

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

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

致谢

克里斯

推荐答案

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

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

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

类似

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)

这篇关于如何在spring-data-mongodb中使用mongodb date函数运行mongodb本机查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆