'Java MongoDB numberLong query - Unable to fetch records
I wanted to fetch records between 1 date to other date from mongodb collection, where dates are stored as long in currenttimemillis. So I specified the query in java as
BasicDBObject query1 = new BasicDBObject();
long startGracePeriodInMillis = 1651676700254;
long endGracePeriodInMillis = 1653466067550;
query1.put("updated_at", new BasicDBObject("$gt", endGracePeriodInMillis).append("$lt", startGracePeriodInMillis));
this query1 is forming as
{"updated_at": {"$gt": {"$numberLong": "1653466067550"}, "$lt": {"$numberLong": "1651676700254"}}}
but im unable to fetch records, as the date is coming as string with $numberLong .. Im able to get records by mentioning only long without numberLong on server directly with
{"updated_at": {"$gt": 1653466067550, "$lt": 1651676700254}}
So what change should i need to make in
query1.put("updated_at", new BasicDBObject("$gt", endGracePeriodInMillis).append("$lt", startGracePeriodInMillis));
to form the query as
{"updated_at": {"$gt": 1653466067550, "$lt": 1651676700254}}
in the query it should come as only number like "$gt": 1653466067550 (which is giving results) but it is coming as "$gt": {"$numberLong": "1653466067550" - which is creating problem
Solution 1:[1]
You have start time and end time, you should search between them:
query1.put("updated_at", new BasicDBObject("$gt", startGracePeriodInMillis)
.append("$lt", endGracePeriodInMillis));
Not the other way around... You are now searching for records that are after your end time or before your start time.
$gt
means "greater than", you probably want to find documents with updated_at
greater than your startGracePeriodInMillis...Same with $lt
, meaning "less than", you probably want document with updated_at
less than your endGracePeriodInMillis.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |