java - 如何在 spring-data-mongodb 中使用 mongodb 日期函数运行 mongodb native 查询?

标签 java spring mongodb spring-data-mongodb

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

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 字符串,请帮忙...

问候

克里斯

最佳答案

您可以使用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)

关于java - 如何在 spring-data-mongodb 中使用 mongodb 日期函数运行 mongodb native 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46612203/

相关文章:

java - Java App 是否显示使用的版本?

java - 用于管理多个 Web 应用程序配置的工具

java - 在所有 SpringBeans 和 ApplicationContext 都被初始化之后调用方法

javascript - 如何在 MongoDB 中结合值匹配和管道运算符?

java - 选择项目中的 JList actionlistener "delay"

java - 检查大文件的保管箱进度

java - spring手动添加bean

java - 导入jar时出现logback问题

Haskell 不明确的类型变量——我迷路了?

mongodb - MongoDB 中的性能扩展(搜索操作)?