I have a bunch of documents in a collection called posts as shown below with their creation date.
I'm trying to retrieve the 10 documents whose creation date is less than the date provided using aggregate query below.
PostModel.aggregate([{
"$match": {
"$and": [{
"organisationId": "wHQcDpJaFqpRmeS7chXlh"
}, {
"createdAt": {
"$lt": {
"$toDate": "2022-12-16T11:30:55.183Z"
}
}
}
]
}
}, {
"$lookup": {
"from": "boards",
"localField": "boardId",
"foreignField": "_id",
"as": "board"
}
}, {
"$sort": {
"createdAt": -1
}
}, {
"$limit": 10
}
]);
Query returns empty result set. Following section below seems problematic because when taken out query returns data.
{ createdAt: { $lt: { $toDate: pageProps?.cursor } } }
There is something wrong with the date timestamp comparison but I couldn't figure it out.
createdAt
property of the document is Date
data-type.
CodePudding user response:
Since you manipulate the compared value with $toDate
, one option is to use $expr
:
db.collection.aggregate([
{$match: {
$and: [
{organisationId: "wHQcDpJaFqpRmeS7chXlh"},
{$expr: {$lt: ["$createdAt", {$toDate: "2022-12-16T11:30:55.183Z"}]}}
]
}}
])
See how it works on the playground example