Find by date without function

115
April 23, 2019, at 05:20 AM

I have a mongodb collection with a date property. I need to find some objects that has a date greater than a literal date string. I'm using node.js native driver. And I receive the date as string. When I try this, doesn't work:

db.myCollection.find({ 
        'dateField': { $gte : "1974-11-18T02:00:00.000Z"  }
}).count()

This doesn't work too:

db.myCollection.find({ 
        'dateField': { $gte : {$date: '1974-11-18T02:00:00.000Z'}  }
}).count()

But this works:

db.myCollection.find({ 
        'dateField: { $gte : ISODate("1974-11-18T02:00:00.000Z")  }
}).count()  

How can I query a mongodb by date without use Date() or ISODate() functions?

Edit:

I can't use function because on my nodejs app I have this object:

let conditions = {}
conditions['dateField'] = "1974-11-18T02:00:00.000Z"
let rows = await db.collection('myCollection').aggregate([
    {$match: conditions},
    {$count: "total"}
]).toArray()

So I can't pass a "function" on conditions object to $match on mongodb, because this doesn't work:

conditions['dateField'] = new Date("1974-11-18T02:00:00.000Z")
Answer 1

type of the date saved inside your database is a Date object not an String and that's why your both the above queries fails because there you are using String date. and therefore, you must have to convert your String dates to Date object to get the result.

You can use moment library to convert String date to Date object. Something like

db.myCollection.find({ 
  "dateField": { "$gte": moment("1974-11-18T02:00:00.000Z").toDate() }
}).count() 

Even with the Date() function

db.myCollection.find({ 
  "dateField": { "$gte": new Date("1974-11-18T02:00:00.000Z") }
}).count() 
Rent Charter Buses Company
READ ALSO
Display formating of javascript object, through node

Display formating of javascript object, through node

I've been puzzled by this for a whileLet's take this simple object:

150
THREE.js freezes after I splice 3dObject from array

THREE.js freezes after I splice 3dObject from array

I have a online realtime game I am creatingAll of my players and their animation mixers are stored in arrays

157
I have several arrays of text values and I want to select one of the arrays to use as an HTML datalist

I have several arrays of text values and I want to select one of the arrays to use as an HTML datalist

I have several arrays of text values and I want to use one of them to populate an HTML datalist based on the user's selection of the value in another datalistI don't know how to code this

129
Expand section on click with smooth animation

Expand section on click with smooth animation

I can't get a smooth drop down animation to work on my section

148