I want to aggregate data of my mongoose Schema so that I get data of particular month. I used match with aggregate using gte and lt operators but if only single match operator (gte or lt) given only it works.
My order schema is as follows:
const OrderSchema = new Schema({
_id: Schema.Types.ObjectId,
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, required: false },
//....................
productId: { type: Schema.Types.ObjectId, ref: "products" },
productName: { type: String, required: false },
productQuantity: { type: Number, required: false },
totalAmount: { type: Number, required: false },
});
Now, I need to find total top five products sold out this month, on the basis of productQuantity. I tried using both matching createdAt field with gte with some date and lte with some date. But, if used both at once, result is not returned but when using one at a time, the result is returned.
Order.aggregate([
{
$match: {
createdAt: { //schema contains createdAt field with Date.now()value
$gte: Date("2019-04-30"),
$lt: Date("2019-05-10")
}
}
}])
But using one at a time
Order.aggregate([
{
$match: {
createdAt: {
$gte: Date("2019-04-30")
}
}
$group: {
_id: "$productId",
created: { $first: "$createdAt" },
count: { $sum: "$productQuantity" }
}
}
{
$sort: {
count: -1
}
},
{ $limit: 5 }
}
])
it works.But I need to find the top sold products within a interval of month given the month. I did this way
Order.aggregate([
{
$match: {
createdAt: {
$gte: startDate
}
},
$group: {
_id: "$productId",
created: { $first: "$createdAt" },
count: { $sum: "$productQuantity" }
}
},
{
$sort: {
count: -1
}
},
{ $limit: 5 }
])
But this gives message": "Arguments must be aggregate pipeline operators" error. Why am i having such problem?