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 :-)
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.
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")
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.
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) }
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With