Reputation: 17298
I am trying to list last 5 days result by writing mongodb queries.
Date.prototype.addDays = function(h) {
this.setTime(this.getTime() + (h*60*60*1000*24));
return this;
}
var beforeDate = (new Date()).addDays(-5);
var result = db.xxx.find( { CreatedDate: { $lt: beforeDate } } )
.map(function (doc) { return doc._id; });
print("----");
print(result);
but result is not meaningful. How can I list my data in mongodb collection in last 5 days writing simple query.
Script executed successfully, an empty result returned.
// Command #3 8:1 0,387 s
Script executed successfully, an empty result returned.
// Command #4 12:5 0,001 s
----
// Command #5 13:5 0,003 s
BinData(3,"FJguxz9zEk6e+is8JKRJGw=="),BinData(3, . . . . . ."
Upvotes: 0
Views: 42
Reputation: 4210
For last 5 days data you should have query like:
db.drt.find({ date: { $gt: new Date("2019-07-21T11:44:16.082Z") } })
And the javascript logic would be as below:
Date.prototype.addDays = function(h) {
this.setTime(this.getTime() + (h*60*60*1000*24));
return this.toISOString();
}
var beforeDate = (new Date()).addDays(-5);
console.log(beforeDate);
Note: Don't use
limit
. It will give you only 5 records where we need last 5 days records that can be possible multiples.
Hope this help!
Upvotes: 1
Reputation: 2166
I have this sample data,
/* 1 createdAt:26/07/2019, 15:53:51*/
{
"_id" : ObjectId("5d3ad4b7a8672903e950a0c2"),
"date" : ISODate("2019-07-19T13:55:09.000+05:30")
},
/* 2 createdAt:26/07/2019, 15:53:47*/
{
"_id" : ObjectId("5d3ad4b3a8672903e950a0c1"),
"date" : ISODate("2019-07-20T13:55:09.000+05:30")
},
/* 3 createdAt:26/07/2019, 15:53:44*/
{
"_id" : ObjectId("5d3ad4b0a8672903e950a0c0"),
"date" : ISODate("2019-07-21T13:55:09.000+05:30")
},
/* 4 createdAt:26/07/2019, 15:53:41*/
{
"_id" : ObjectId("5d3ad4ada8672903e950a0bf"),
"date" : ISODate("2019-07-22T13:55:09.000+05:30")
},
/* 5 createdAt:26/07/2019, 15:53:36*/
{
"_id" : ObjectId("5d3ad4a8a8672903e950a0be"),
"date" : ISODate("2019-07-23T13:55:09.000+05:30")
},
/* 6 createdAt:26/07/2019, 15:53:34*/
{
"_id" : ObjectId("5d3ad4a6a8672903e950a0bd"),
"date" : ISODate("2019-07-24T13:55:09.000+05:30")
},
/* 7 createdAt:26/07/2019, 15:53:30*/
{
"_id" : ObjectId("5d3ad4a2a8672903e950a0bc"),
"date" : ISODate("2019-07-25T13:55:09.000+05:30")
},
/* 8 createdAt:26/07/2019, 15:53:26*/
{
"_id" : ObjectId("5d3ad49ea8672903e950a0bb"),
"date" : ISODate("2019-07-26T13:55:09.000+05:30")
}
You need to make the query,
db.drt.find({ date: { $lt: date } }).limit(5)
Upvotes: 1