简体   繁体   中英

MongoDB Date query JAVA

Im trying to do a query to get all the values from my DB wich each have a date. One example:

leadTime: [
    {
      date: ISODate("2014-03-19T23:00:00Z"),
      value: 25.8
    },
    {
      date: ISODate("2014-03-20T23:00:00Z"),
      value: 31.299999999999997
    },
    {
      date: ISODate("2014-03-21T23:00:00Z"),
      value: 34.4
    }
]
enter code here

My code is:

DBObject query=new BasicDBObject("group",group);
DBObject serieData= col.findOne(query,new BasicDBObject(serie, 1));
if (serieData != null) {
List<DBObject> data = (List<DBObject>) serieData.get(serie);
for (DBObject item : data) {
    result.add(new HistoryData((Date) item.get("date"),(Double) item.get("value")));
}

Now I want to get the values that the date is bigger than a date that I pass by parameter. The query I did is this:

DBObject query=new BasicDBObject("group",group)
        .append("date", new BasicDBObject("$gte", parameterDate))
        ;

But I always receive the result empty, can you help me? sorry for my english and than

Assuming that leadTime is a field in your documents, your query has to look like this

DBObject query=new BasicDBObject("group",group)
    .append("leadTime.date", new BasicDBObject("$gte", parameterDate))
    ;

The way you did it, MongoDB would have searched for a date field in your document root:

{ _id: "Foo",
  date: ISODate("2014-03-19T23:00:00Z"),
  [...]
}

Queries in MongoDB don't make a difference if the queried field is a single value or an array, so using the dot notation on a field which holds an array of subdocuments is perfectly valid.

What you want to do is not possible with a simple query. But if you still want to do it in mongodb you need to use the aggregation framework, with something like that :

db.<col_name>.aggregate( [ { $unwind : "$group" }, { $match : {'group.date': { $gte : parameterDate } } ] )

this a js command, but you should be able to translate it easly in Java Driver (you can also add a $project operation to just return needed fields).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM