user2402616
user2402616

Reputation: 1563

Mongo match aggregate not working with date

I'm using mongoose and the following works just fine.

const TODAY = moment().format('YYYY-MM-DD');
const todaysFoos = await Foo.find({updatedAt: { $gte: TODAY }, someField: { $ne: '' } });

Where updatedAt is created/updated by using the timestamps: true in the Mongoose Model

However, I'm unable to get this to work with an aggregate const mapping = { alias: "$someField" };

 const pipeline = [
    { $match: { updatedAt: { $gte: TODAY }, someField: { $ne: '' } } },
    { $project: mapping }
];

const todaysFoos = await Foo.aggregate(pipeline);
                                            

I keep getting nothing back from the aggregate whereas the first find works just fine. Any ideas?

Upvotes: 0

Views: 675

Answers (2)

Udor Blessing
Udor Blessing

Reputation: 11

I just had the same issue and for anyone looking for a solution.

You can check out Mongo: dates in match aggregate query seem to be ignored

Apparently, match works with new Date(your_date)

Therefore the logic will be

const TODAY = new Date();
const pipeline = [
    { $match: { updatedAt: { $gte: TODAY }, someField: { $ne: '' } } },
    { $project: mapping }
];
const todaysFoos = await Foo.aggregate(pipeline);

Upvotes: 1

user2402616
user2402616

Reputation: 1563

I had to do

let TODAY = moment().format('YYYY-MM-DD');
TODAY = new Date(TODAY);

I don't know this is needed for $match but it works in find. Does anybody know?

Upvotes: 0

Related Questions