Convert Field With Unix TimeStamp to Date (Mongodb/NodeJS) - node.js

I am using aggregate in MongoDB to group fields by $year, $month & $dayOfMonth.
Transaction.aggregate(
[{
$group: {
_id: {
year : { $year : "$createdAt" },
month : { $month : "$createdAt" },
day : { $dayOfMonth : "$createdAt" },
},
totalQuantity: {
$sum: "$totalQuantity"
},
totalAmount: {
$sum: "$totalAmount"
},
totalPayment: {
$sum: "$totalPayment"
},
count: { $sum: 1 }
}
}
]).then( res => console.log(res));
In the above code, I'm using the default $createdAt field but when I try to use $date which has the date in Unix timestamp, it throws an error.
What have I tried?
Transaction.aggregate(
[{
$group: {
_id: {
year : { $year : new Date("$date") },
month : { $month : new Date("$date") },
day : { $dayOfMonth : new Date("$date") },
},
totalQuantity: {
$sum: "$totalQuantity"
},
totalAmount: {
$sum: "$totalAmount"
},
totalPayment: {
$sum: "$totalPayment"
},
count: { $sum: 1 }
}
}
]).then( res => console.log(res));
But this didn't work as "$date" is passed as a string to the Date constructor. Any workaround this?

You can do it with $toDate, converts unix timestamp milisecond to iso date,
$addFields to convert createdAt and replace value
{
$addFields: {
createdAt: { $toDate: "$createdAt" }
}
},
you can use directly in $group
{
$group: {
_id: {
year: { $year: "$createdAt" },
month: { $month: "$createdAt" },
day: { $dayOfMonth: "$createdAt" }
}
}
}
Playground: https://mongoplayground.net/p/-gWq0YLtLSX
you can convert inside $group also, but this will convert three time and instead of this you can add one time and use in group like above example.
year: { $year: { $toDate: "$createdAt" } },
month: { $month: { $toDate: "$createdAt" } },
day: { $dayOfMonth: { $toDate: "$createdAt" } }

Related

How do you count records for the current month?

Using mongo or mongoose, how would I get the total number of records for the current month?
I have this but it is giving me a total for every month, I just want a count of records for the current month.
const genTotal = await General.aggregate([
{
$group: {
_id: {
year: { $year: "$visitDate" },
month: { $month: "$visitDate" },
},
Total: { $sum: 1 },
},
},
]);
I also tried this:
const genTotal = await General.aggregate([
{
$group: {
_id: {
month: { $month: "$visitDate" },
},
Total: { $sum: 1 },
},
},
{
$match: { $month: 3 },
},
]);
Add a match stage in the beginning to filter out the past month's documents try this:
let month = new Date().getMonth();
const genTotal = await General.aggregate([
{
$match: {
$expr: {
$eq: [{ $month: "$visitDate" }, month]
}
}
},
{
$group: {
_id: {
year: { $year: "$visitDate" },
month: { $month: "$visitDate" },
},
Total: { $sum: 1 }
}
}
]);

$project , $match returns values and then group by returns null in mongodb

I am new to mongodb. I want to total for given week of year. I have used aggregate function in which I have used $project then $match then $group. It returns null value. But When I use aggregate function with $project and $match only. In that case it returns documents.
filteredOrders = await Order.aggregate([
{
$project: {
day: { $dayOfWeek: '$createdAt' },
week: { $week: '$createdAt' },
month: { $month: '$createdAt' },
year: { $year: '$createdAt' },
total: '$totalPrice',
},
},
{ $match: { week: 10, year: 2021 } },])
The above code returns documents.
But
filteredOrders = await Order.aggregate([
{
$project: {
day: { $dayOfWeek: '$createdAt' },
week: { $week: '$createdAt' },
month: { $month: '$createdAt' },
year: { $year: '$createdAt' },
total: '$totalPrice',
},
},
{ $match: { week: 9, year: 2021 } },
{
$group: {
_id: {
createdAtDay: { $dayOfWeek: '$createdAt' },
createdAtWeek: { $week: '$createdAt' },
createdAtMonth: { $month: '$createdAt' },
createdAtYear: { $year: '$createdAt' },
},
count: { $sum: '$totalPrice' },
},
},
]);
The above code returns null for all elements in _id and returns 0 in count.
Please help me...
You need to use newly projected field from previous stage for the next $group stage
filteredOrders = await Order.aggregate([
{
$project: {
day: { $dayOfWeek: '$createdAt' },
week: { $week: '$createdAt' },
month: { $month: '$createdAt' },
year: { $year: '$createdAt' },
total: '$totalPrice',
},
},
{ $match: { week: 9, year: 2021 } },
{
$group: {
_id: {
createdAtDay: '$day',
createdAtWeek: '$week',
createdAtMonth: '$month',
createdAtYear: '$year',
},
count: { $sum: '$total' },
},
},
]);

not getting data if i choose same date for from and to

i am doing date range using mongoose aggregation when i choose two different dates am getting data but when choose same date am not getting data on perticular date,for example if i choose 23 and 24 dates am getting data but when i choose 23 & 23 am not getting data ,please help me to fix the issue
if(from && to ) {
let fromdate = moment(from).format();
let todate = moment(to).format()
console.log(new Date(fromdate),new Date(todate),'dfdfd')
console.log(fromdate,todate,'dfdfd')
return await Message.aggregate([
{
$match: {unanswered: true}
},
{
$match: {
createdAt: {
$gte: new Date(fromdate),
$lte: new Date(todate)
}
}
},
{
$group: {
_id: {$toLower: '$message'},
id: {$first: '$_id'},
display: {$first: '$message'},
createdAt: {$first: '$createdAt'},
totalQuantity: {$sum: 1}
}
}
]).sort({totalQuantity: 'desc'});
}```
Why you don't use $gte function for greater than or equal ?
[{
$match: {
"unanswered": true
}
},
{
$match: {
"createdAt": {
$gte: new Date(fromdate),
$lte: new Date(todate)
}
}
},
{
$group: {
_id: {
$toLower: '$message'
},
id: {
$first: '$_id'
},
display: {
$first: '$message'
},
createdAt: {
$first: '$createdAt'
},
totalQuantity: {
$sum: 1
}
}
}
]

how to group data based on months in nodejs?

Sale.aggregate({
$match: filter
}, {
$group: {
"_id": {
"store_id": "$store_id",
//"created_on": { $dateToString: { format: "%Y-%m-%d", date: "$strBillDate" } }
},
month: {
$month: "$strBillDate"
},
store_id: {
$first: "$store_id"
},
strBillAmt: {
$sum: "$strBillAmt"
},
strBillNumber: {
$sum: 1
}
}
})
Instead of date, I need to group sales in months, how to group sales in months in nodejs
I used a projection first in the aggregate chain to extract monthly and yearly values and did the grouping afterwards:
<doc-name>.aggregate([
{ $project:
{ _id: 1,
year: { $year: "$date" },
month: { $month: "$date"},
amount: 1
}
},
{ $group:
{ _id: { year: "$year", month: "$month" },
sum: { $sum: "$amount" }
}
}])
I also tried with your model:
var testSchema = mongoose.Schema({
store_id: { type: String },
strBillNumber: { type: String },
strBillDate: { type: Date },
strBillAmt: { type: Number }
});
var Test = mongoose.model("Test", testSchema);
Create some test data:
var test = new Test({
store_id: "1",
strBillNumber: "123",
strBillDate: new Date("2016-04-02"),
strBillAmt: 25
});
var test2 = new Test({
store_id: "1",
strBillNumber: "124",
strBillDate: new Date("2016-04-01"),
strBillAmt: 41
});
var test3 = new Test({
store_id: "3",
strBillNumber: "125",
strBillDate: new Date("2016-05-13"),
strBillAmt: 77
});
Run the query:
Test.aggregate([
{ $project:
{ store_id: 1,
yearBillDate: { $year: "$strBillDate" },
monthBillDate: { $month: "$strBillDate" },
strBillAmt: 1
}
},
{ $group:
{ _id: {yearBillDate: "$yearBillDate", monthBillDate:"$monthBillDate"},
sum: { $sum: "$strBillAmt" }
}
}
], function(err, result) {
console.log(err, result)});
And got a reasonable result:

Sort on nested column with aggregation

I have following query using aggregation framework in Mongoose:
Comment.aggregate([{
$match: {
isActive: true
}
}, {
$group: {
_id: {
year: {
$year: "$creationDate"
},
month: {
$month: "$creationDate"
},
day: {
$dayOfMonth: "$creationDate"
}
},
comments: {
$push: {
comment: "$comment",
username: "$username",
creationDate: "$creationDate",
}
}
}
}, {
$sort: {
'comments.creationDate': -1
}
}, {
$limit: 40
}], function (err, comments) {
//...
});
Finally, I want to sort the records using creationDate inside comments array. I've used comments.creationDate but it doesn't work!
What is the correct approach to sort items using aggregation framework?
You need to move your $sort on creationDate above the $group so that it affects the order the comments array is built using $push. As you have it now, you're sorting the overall set of docs, not the array.
Comment.aggregate([{
$match: {
isActive: true
}
}, {
$sort: {
creationDate: -1
}
}, {
$group: {
_id: {
year: {
$year: "$creationDate"
},
month: {
$month: "$creationDate"
},
day: {
$dayOfMonth: "$creationDate"
}
},
comments: {
$push: {
comment: "$comment",
username: "$username",
creationDate: "$creationDate",
}
}
}
}, {
$limit: 40
}], function (err, comments) {
//...
});

Resources