如何使用Spring mongoTemplate获取带有条件和日期范围的集合字段?

时间:2016-11-16 11:51:07

标签: mongodb spring-data spring-mongo spring-mongodb

我想将以下控制台mongodb查询转换为Spring mongoTemplate查询

db.transaction.find({"account_number":10}, {"entry_date":{"$gte": new ISODate("2016-07-20"),"$lte": new ISODate("2016-07-21")}}).count()

我试过以下

 Query query = new Query();
        Criteria criteria =
                Criteria.where("account_number").is(accountNumber).and("account_code").is(accountCode)
                .and("entry_date").gte(start).lte(end);
        query.addCriteria(criteria);
        mongoTemplate.find(query, Transaction.class, "transaction");
        return mongoTemplate.find(query, Transaction.class, "transaction");

调试时,我将上面的代码翻译成以下查询值。查询没有返回我在mongo控制台上得到的相同结果。

Query: { "account_number" : 10 , "account_code" : 2102 , "entry_date" : { "$gte" : "2015-05-20" , "$lte" : "2016-07-21"}}

问题是我如何构建一个查询来传递两个不同的条件,就像我在控制台上做的那样?

我想要实现的是获取给定account_number的两个日期(包括)之间的所有交易。

收藏结构

    {
    "_id" : ObjectId("5825e49585a4caf2bfa30ff4"),
    "profit" : "",
    "account_number" : 280,
    "m_number" : "",
    "registration_number" : "",
    "page_number" : "",
    "entry_date" : ISODate("2014-10-20T07:33:57Z"),
    "narration" : "To cash",
    "voucher_number" : "",
    "debit_credit" : -4400,
    "account_code" : 2105,
    "created_at" : ISODate("2014-10-20T07:33:57Z"),
    "updated_at" : ISODate("2014-10-20T07:33:57Z"),
    "employee_id" : 0,
    "balance" : 0,
    "credit" : 0,
    "debit" : 0,
    "particulars" : "",
    "since_last" : 0,
    "transaction_type" : 0,
    "voucher_path" : "",
    "branch" : "",
    "auto_voucher_number" : "",
    "check_book_series" : ""
}
{
    "_id" : ObjectId("5825e49585a4caf2bfa30ff5"),
    "profit" : "",
    "account_number" : 1555,
    "m_number" : "",
    "registration_number" : "",
    "page_number" : "",
    "entry_date" : ISODate("2014-10-20T07:33:57Z"),
    "narration" : "To",
    "voucher_number" : 73804,
    "debit_credit" : -1550,
    "account_code" : 2101,
    "created_at" : ISODate("2014-10-20T07:33:57Z"),
    "updated_at" : ISODate("2014-10-20T07:33:57Z"),
    "employee_id" : 0,
    "balance" : 0,
    "credit" : 0,
    "debit" : 0,
    "particulars" : "",
    "since_last" : 0,
    "transaction_type" : 0,
    "voucher_path" : "",
    "branch" : "",
    "auto_voucher_number" : "",
    "check_book_series" : ""
}

解决方案 原始查询仅返回account_number = 10的记录并忽略entry_date条件。我想这是错误的查询方式。这是正确的解决方案

   DateTime start, DateTime end;

        Query query = new Query();
        Criteria criteria =
                Criteria.where("account_number").is(accountNumber).and("account_code").is(accountCode)
                .and("entry_date").gte(start).lte(end);
        query.addCriteria(criteria);

        return mongoTemplate.find(query, Transaction.class, "transaction");
  

重要的是日期格式正确。例如,java.util.Date或JODA DateTime

1 个答案:

答案 0 :(得分:0)

您将日期作为字符串传递。尝试将开始日期和结束日期作为java.util.Date类型传递。例如

CMTimeMakeWithSeconds( newDurationSeconds, 1000*1000*1000 )