I want to get previous month data using mongoose in MongoDB. Actually I am not getting proper solution. If current month is November, then I need October (previous) month’s data. If current month is December then I need November month’s data. How can I sort using mongoose.
db.find({
...Here I need to define month
)}
Please remember I need last month data only, not last 30 days data.
I have a example-
const current = new Date();
var lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
const income = await this.incomeModel.find({
createdAt: {
$gte: new Date(lastMonth),
$lte: current
}
});
This example gives me last 30 days data. But I need last month data.
Here are two documents-
{
"_id": {
"$oid": "635e4156ffcee58387c0589e"
},
"seller": {
"$oid": "635ce812583711421229422d"
},
"user": {
"$oid": "635ce77e5837114212294222"
},
"address": {
"$oid": "6353aaf0fa6a1b0124c22532"
},
"orderId": {
"$oid": "635e309f70a314e09df4c9ed"
},
"products": [
{
"productId": {
"$oid": "635cee1bf0a34d127f5403a6"
},
"quantity": 2
}
],
"income": 850,
"paySuccess": true,
"createdAt": {
"$date": {
"$numberLong": "1666257494398"
}
},
"updatedAt": {
"$date": {
"$numberLong": "1667136287762"
}
},
"__v": 0,
"refunded": "Cancelled"
}
This is created on 20 October 2022,
{
"_id": {
"$oid": "635e416effcee58387c058a7"
},
"seller": {
"$oid": "635ce812583711421229422d"
},
"user": {
"$oid": "635ce77e5837114212294222"
},
"address": {
"$oid": "6353aaf0fa6a1b0124c22532"
},
"orderId": {
"$oid": "635e30e170a314e09df4c9f6"
},
"products": [
{
"productId": {
"$oid": "635cee33f0a34d127f5403b0"
},
"quantity": 2
}
],
"income": 850,
"paySuccess": true,
"createdAt": {
"$date": {
"$numberLong": "1667467118696"
}
},
"updatedAt": {
"$date": {
"$numberLong": "1667481887762"
}
},
"__v": 0
}
Another document created on 03 November 2022
Now I need to get last month data only. As from two documents, the first one is created on last month, I need to find the first one document only.
5
You can use $dateDiff
to compute the date difference with $$NOW
in month unit. Get it with $eq
to get the last month data.
db.collection.find({
$expr: {
$eq: [
1,
{
"$dateDiff": {
"startDate": "$createdAt",
"endDate": "$$NOW",
"unit": "month"
}
}
]
}
})
Mongo Playground