daltonfury42
daltonfury42

Reputation: 3742

MongoDB: How to get documents older than 30 days?

I know this question has been asked before, but it's not working for me. I am very sorry for asking this again.

I have a table in which each document has a addedon field:

{ "_id" : ObjectId("..."),
...
"addedon" : "Nov 21, 2018 8:09:35 AM", 
...
}

I want to get all documents which are older than 30 days:

db.mycollection.find({"addedon":{$lt: new Date(Date.now() - 30*24*60*60 * 1000)}})

But the results come out as empty. Can anyone point out what I am doing wrong?

Upvotes: 1

Views: 2644

Answers (1)

TeTeT
TeTeT

Reputation: 2094

You have to revert to javascript when the addedon field is a string:

db.dateasstring.find({ $where: function() {
    return (new Date(this.addedon) < new Date(Date.now() - 30*24*60*60 * 1000));
}})

Upvotes: 2

Related Questions