MongoDB java驱动程序获取记录的位置和用户之间的日期

时间:2014-11-20 14:38:58

标签: java mongodb date nosql

从名为"人员" 的集合中,我想要检索所有日期介于

之间的记录
"14-11-2014" and "20-11-2014"  <-- These are both in string format (dd-mm-yyyy)

user: "Erik"

我的mongoDB

{
  "_id" : "546c9f26dbeaa7186ab042c4",          <------this one should NOT be retreived
  "Task: "Sometask"                                                because of the user
  "date" : "20-11-2014",
  "user" : "Dean"
},
{
  "_id" : "546caef6dbeaa7186ab042c5",          <--------- This one should be retreived
  "task": "A task",
  "date" : "20-11-2014",
  "user" : "Erik"
}
{
  "_id" : "546caef6dbeaa7186ab042c5",          <----- This one should NOT be retreived
  "task": "A task",                                         because of the date
  "date" : "13-11-2014",
  "user" : "Erik"
}

我正在使用java mongo java driver 2.11.3

也许使用BasicDBObject有一些解决方案?

我非常好奇..谢谢

修改

我正在使用:

public static String findTimelines(String begin, String end, String username) throws UnknownHostException, JSONException{
    DBCollection dbCollection = checkConnection("timelines");
    BasicDBObject query = new BasicDBObject();
    query.put("date", BasicDBObjectBuilder.start("$gte", begin).add("$lte",end).get());
    query.put("user", username);
    dbCollection.find(query).sort(new BasicDBObject("date", -1));
    DBCursor cursor = dbCollection.find(query);
    return JSON.serialize(cursor);
}

直到你查询类似&#34; 28-11-2014&#34;至于&#34; 01-12-2014&#34;,即使有一个带有日期的对象,它也不会返回任何内容:&#34; 30-11-2014&#34;。我想这是因为月份的变化 同样当您执行以下操作时,该对象将被检索:&#34; 28-11-2014&#34;到&#34; 30-11-2014&#34;因为这个月保持不变

请帮忙!

2 个答案:

答案 0 :(得分:3)

尝试这样的事情

BasicDBObject query = new BasicDBObject();
query.put("date", BasicDBObjectBuilder.start("$gte", fromDate).add("$lte", toDate).get());
collection.find(query).sort(new BasicDBObject("date", -1));

答案 1 :(得分:1)

这是您要使用的查询:

db.posts.find({date: {$gte: start, $lt: end}, user: 'Erik'});

您应首先使用SimpleDateFormat或类似方式解析日期以获取Date个对象。

然后使用BasicDBObject

整理您的查询
BasicDBObject q = new BasicDBObject();
q.append("date", new BasicDBObject().append("$gte", start).append("$lt", end));
q.append("user", "Erik");

collection.find(q);