Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB greater than numberLong issue

I am trying to get all documents in a collection in which the date, stored as this:

{
  "_id": {
    "$oid": "5c500ff8df157e051961cfab"
  },
  "date": {
    "$date": {
      "$numberLong": "1548750839931"
    }
  },
  "when": "2019-1-29T8:33Z",
  "score": 20
}

... is greater than this: 1546300800000

I have 2 records in my collection, but I get none in return?

Here is my query:

{"date":{"$gt": 1546300800000}}

I guess that is has something to do with the date is stored as string, but can it be done?

Hoping for help and many thanks in advance :-)

like image 521
Mansa Avatar asked Feb 02 '19 13:02

Mansa


People also ask

How do you do greater than in MongoDB?

You can use the following operators in MongoDB to perform greater than or less than queries: $lt: Less than. $lte: Less than or equal. $gt: Greater than.

What is NumberLong in MongoDB?

NumberLong. The mongo shell treats all numbers as floating-point values by default. The mongo shell provides the NumberLong() wrapper to handle 64-bit integers. The NumberLong() wrapper accepts the long as a string: NumberLong("2090845886852")

Is $gt for greater than or equal to the value?

Definition. $gt selects those documents where the value of the field is greater than (i.e. > ) the specified value . For most data types, comparison operators only perform comparisons on fields where the BSON type matches the query value's type.


1 Answers

Your date is saved as Date type and you are using timestamp to find the documents.

So, You can first convert date to timestamp using $toLong aggregation operator and then use $gt operator

If you are using mongodb 4.0

db.collection.find({
  "$expr": {
    "$gt": [{ "$toLong": "$date" }, 1546300800000]
  }
})

If you are using mongodb 3.6

db.collection.find({
  "$expr": {
    "$gt": [
      { "$subtract": ["$date", new Date("1970-01-01")] },
      1546300800000
    ]
  }
})

or you can simply convert your timestamp to type date

db.collection.find({
  "date": { "$gt": new Date(1546300800000) }
})
like image 189
Ashh Avatar answered Sep 21 '22 04:09

Ashh