My mongodb query is not returning any results and I can't spot why.
Here is the relevant contents of my data:
> db.reports.find({},{endDate:1})
{ "_id" : ObjectId("5182882ae4b032c67674c494"), "endDate" : ISODate("2013-05-02T15:37:11.032Z") }
{ "_id" : ObjectId("51828859e4b032c67674c495"), "endDate" : ISODate("2013-05-02T15:37:57.749Z") }
So I have two entries with dates 2013-05-02 15:37:11-57
I want to find all entries with a date less than or equal to that latest date, but I get no results using this query:
db.reports.find({ "endDate" : { "$lte" : { "$date" : "2013-05-02T15:37:11.032Z"}}},{endDate:1})
I am generating the query in java using:
BasicDBObject oldReportSelector = (BasicDBObject) BasicDBObjectBuilder.start()
.add("endDate",
BasicDBObjectBuilder.start().add("$lte",myDate).get())
.get();
What am I doing wrong here?
Edit to add:
myDate is calculated using:
Date endDate = new Date()
Date myDate = new Date(endDate.getTime()-(interval*quantityArchivedReports));
Currently interval = 86400000 and quantityArchivedReports = 4
The reason you are not getting anything in the shell is that you are not using the date format the shell expects. Try changing your query to:
> db.reports.find({ "endDate" : { "$lte" : new Date("2013-05-02T15:37:11.032Z")}})
{ "_id" : ObjectId("5182882ae4b032c67674c494"), "endDate" : ISODate("2013-05-02T15:37:11.032Z") }
You can then use the shell to verify if your code has actually generated a correct date to get back any data or not.
Related
I need to filter my data from mongo db collection by date.
I created following query for complete this task:
new Criteria(Constants.MONGO_POST_CREATION_DATE).gte(DateUtil.getUTCDate(searchDTO.getStartDate())
this criteria generates following query:
{ "creationTime" : { "$gte" : { "$date" : "2018-10-28T21:00:00.000Z"} , "$lte" : { "$date" : "2019-02-06T08:29:00.000Z"}}}
But i couldn't get any data by using this query. It just returns empty result list. I've found following question on stackoverflow which explains how to write correct query for filtering by Date:
Question
So, with query from that answer i'm able to get expected result from mongo:
{ "creationTime" : { "$gte" : new Date("2019-01-24T21:00:00.000Z") , "$lte" : new Date("2019-02-06T08:29:00.000Z")}}
What do i need to change to force Criteria generate proper query for Date?
What is the equivalent of the following Mongo query in Morphia?
db.events.find({ "date": { $gte: ISODate("2001-01-01") , $lt: ISODate("2001-01-02")} })
Currently I have the following code
Query<Event> query = dataStore.find(Event.class);
query.field("date").greaterThanOrEq(startDate).field("date").lessThan(endDate);
but it results in the following Mongo query
{ "$and" : [ { "date" : { "$gte" : { "$date" : "2001-01-01T00:00:00.000Z"}}} , { "date" : { "$lt" : { "$date" : "2001-01-02T00:00:00.000Z"}}}]}
I suppose the end result is the same, but the resulting query is more verbose.
Use criteria with add method
Something like
Query<Event> query = datastore.find(Event.class);
query.criteria("date").greaterThanOrEq(startDate).add(query.criteria("date").lessThan(endDate));
You need to create a query then add date range condition like followed.
Query<Event> queryForEvent = ds.createQuery(Event.class);
queryForEvent.field("date").greaterThanOrEq(startDate);
queryForEvent.field("date").lessThan(endDate);
List<Event> eventList = queryForEvent.asList();
Hoping you will find it useful.
I am using MongoDB 3 and I'm trying to get all purchases by day. The problem is that I have the following value in mongo:
"createDate" : ISODate("2016-04-11T17:57:12.960Z")
And I want to get all the purchases using the following date format dd/MM/yyyy. This is my method:
public List<Purchase> getPurchasesByDate(BigInteger company, Date date, PurchaseStatus status) {
Query query = new Query();
query.addCriteria(Criteria.where("createDate").lte(date).and("status").is(status.toString()).and("company").is(company.toString()));
return mongoTemplate.find(query, Purchase.class);
}
This is what I seeing into mongo console:
{ "createDate" : { "$lte" : { "$date" : "2016-04-11T19:14:56.322Z"} } , "status" : "PAYED" , "company" : "1"}
Obviously is not returning any values. I'm calling my method like this getPurchasesByDate(1, new Date(), PurchaseStatus.PAYED).
Does anybody knows how can I can get all documents by date using this format dd/MM/yyyy?
thanks
I am trying to create a query using MongoDB Java Driver as part of an aggregation command. Currently I allow a date range or an array of specific dates as an argument. eg
<date>
<start>2013-12-10 00:00:00.000</start>
<end>2013-12-12 23:59:59.999</end>
</date>
or
<date>
<specificDates>2013-12-10 00:00:00.000,2013-12-13 00:00:00.000</specificDates>
</date>
The date range query works fine, I parse and convert the xml into a DBObject that produces the following query in mongo;
{ "$match" : { "d" : { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"} , "$lt" : { "$date" : "2013-10-04T00:00:00.000Z"}}}}
For the specificDates I want to return only results that occur between 00:00:00.000 on the given day and 00:00:00.000 of the next day. From my pretty basic knowledge of mongo querys i had hoped to do a similar $match as the date range, but have it use $in on an array of date ranges similar to the following;
{ "$match" : { "d" : { "$in" : [ { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"} , "$lt" : { "$date" : "2013-10-02T00:00:00.000Z"}} , { "$gte" : { "$date" : "2013-10-03T00:00:00.000Z"} , "$lt" : { "$date" : "2013-10-04T00:00:00.000Z"}}]}}}
The above query fails to return any results. I have noticed that $in is not listed in the mongodb manual under the Mongo Aggregation Framework section, but its not throwing any kind of errors that I would have expected for an unsupported operation.
I think the issue may come from this line in the MongoDB Manual;
If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. , , etc.)
In my collection the date isn't stored in an array, I suppose I could store it in the collections in an single element array? (Actually, decided to try this quickly before I posted, no documents returned when the date entry in the document is stored in a single element array)
Document entry example
{ "_id" : ObjectId("52aea5b0065991de1a56d5b0"), "d" : ISODate("2013-12-15T00:00:11.088Z"), "t" : 1501824, "s" : 0, "e" : 601, "tld" : "uk", "y" : "domain:check", "n" : "removed.co.uk" }
Is anyone able to give me some advice as to how I should do this query? Thank you.
EDIT: I left the Java tag here in case anyone needs my DBObject creation code, though it shouldn't be necessary as the queries posted have been generated by my build.
EDIT2: So as Alan Spencer pointed out I should be using $or rather than $in, a working $or function is below (ignore the different formatting like the use of ISODate(), its just copy pasted from the mongo shell rather than getting output from my program)
{ $match : { $or : [ { d : { $gte : ISODate("2013-10-01T00:00:00.000Z"), $lt : ISODate("2013-10-02T00:00:00.000Z") } }, { d : { $gte : ISODate("2013-10-03T00:00:00.000Z"), $lt : ISODate("2013-10-04T00:00:00.000Z") } } ] } }
I think you're inverting the meaning of the $in.
$in is used to match exactly against a list of possible values, like
{"color":{"$in": ["red","green","blue"]}}
For your use case, you are trying to match if it satisfies the first or second, etc. So, you can use $or - http://docs.mongodb.org/manual/reference/operator/query/or/
{ "$match" : { "d" : { "$or" : [ { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"} , "$lt" : { "$date" : "2013-10-02T00:00:00.000Z"}} , { "$gte" : { "$date" : "2013-10-03T00:00:00.000Z"} , "$lt" : { "$date" : "2013-10-04T00:00:00.000Z"}}]}}}
i have a big problem with mongo db because i want to update a multiple fields with One request.
My Json is :
db.test.findOne();
{
"_id" : ObjectId("51e7dd16d2f8db27b56ea282"),
"ad" : "noc2",
"list" : {
"p45" : {
"id" : "p45",
"date" : ISODate("2014-01-01T12:18:30.568Z"),
"value3" : 21,
"value1" : 100,
"value2" : 489
},
"p6" : {
"id" : "p6"
"date" : ISODate("2013-07-18T12:18:30.568Z"),
"value3" : 21,
"value1" : 100,
"value2" : 489
},
"p4578" : {
"id" : "4578"
"date" : ISODate("2013-07-18T12:18:30.568Z"),
"value3" : 21,
"value1" : 100,
"value2" : 489
}
}
}
I want created a field createdDate for all elements list , if createdDate field doesn't exist or is null.
A request example, what i use for update one field with upsert true in my code java :
db.people.update({"advertiser":"noc2","list.4578.createdDate":{$exists:false}},{$set:{"list.p4578.createdDate":"08/08/08"}});
I tried with java where list.4578 is replaced by variable but is too long for too much fields. If i have 100 fields, i do execute 100 requests.
Look :
public void createdFirstDateField(MongoAccess mongo, String ad,HashMap<String,Object> hfirstDate){
BasicDBObject searchQuery = new BasicDBObject();
Iterator <String> it = hfirstDate.keySet().iterator();
String key="";
while (it.hasNext()){
key=it.next();
searchQuery.append("ad", ad).append(key, new BasicDBObject("$exists", false));
//System.out.println(key);
BasicDBObject doc = new BasicDBObject ();
doc.append("$set",new BasicDBObject(key,new Date()));
mongo.insert(searchQuery, doc); // update with upsert true
}
}
Thanks.
Why don't you use the update with upsert?
db.people.update({"advertiser": "noc2"},
{$set: {"list.$.createdDate": "08/08/08"}},
{$upsert: true);
If the createdDate exists it will be updated, if not it will be inserted.
You can update multiple documents at once, using update Multi. But there in not atomic way to update multiple embedded documents.
You can checkout mongodb positional operator, but this does not fit in your use case.