I want to get user data of the last 6 months from the current date in MongoDB. I am filtering data by status than getting the array in response. I also want to apply another query on same based on date. I want to filter it once based on last 6 months then in another query based on last 30 days from current date. My data is -
{
_id: new ObjectId("63ac23187dc7d"),
details: 'hii there i am feeling great today',
status: '1',
createdAt: 2021-11-28T11:06:00.736Z
},
{
_id: new ObjectId("63ac23b357dc96"),
details: 'hi i am feeling good today',
status: '1',
createdAt: 2022-12-28T11:08:40.400Z,
},
{
_id: new ObjectId("63b2b2afa0d8e"),
details: 'Hello!! This is Ankit and feeling good',
status: '1',
createdAt: 2022-11-14T10:31:36.098Z
},
{
_id: new ObjectId("63b2b2sswa0d91"),
details: 'Felling bad a bit',
status: '1',
createdAt: 2023-01-02T10:32:27.149Z
},
{
_id: new ObjectId("63b2b2a0d94"),
details: 'Hmm, its ok ok',
status: '1',
createdAt: 2023-01-02T10:33:19.386Z
}
CodePudding user response:
We use the $gte query operator and JavaScript's Date.now() function to retrieve all order documents with a date greater than or equal to 6 months before the current date. We will use new Date() of JavaScript to get the current date and the setMonth() method to go back 6 months.
You can try this
let sixMonths = new Date();
sixMonths.setMonth(sixMonths.getMonth() - 6);
db.collections.find({ createdAt: { $gte: sixMonths } });
For the days, you can put "1"instead of "6" which is equivalent to 1 month.