I have Millions of documents in the mongodb collection.
I want to group the documents based on minute and hour interval.
I created the index for timestamp.
I tried below mentioned query, but it’s took too much time or timeout.
[ {
_id: {
interval: {
$minute: {
$toDate: {
$multiply: ["$timestamp", 1000],
},
},
},
},
timestamp: {
$first: "$timestamp",
},
count: {
$sum: 1,
},
} ]
How can i resolve the issue.
I tried with **skip **and **limit **also still i’m facing same issue.
2
Answers
Please check this, may it will helpful.
To group millions of documents based on intervals using MongoDB, you can utilize the aggregation framework and the $bucket operator. The $bucket operator allows you to group documents into buckets based on specified boundaries.
Here’s an example of how you can use the $bucket operator to group documents based on intervals:
In the above example:
Make sure to replace collection, fieldToGroupBy, and the interval boundaries with your actual values.
This query will return the grouped documents along with the count of documents in each interval. You can modify the output fields as per your requirements.
The $bucket operator is available starting from MongoDB version 3.4.