Reputation: 522
I'm trying to pull from an array in a mongo document using a value by comparing an isodate string older than 60 days using a mongo query, but it is not pulling the data from the array in the document. For example the document below should only have job 3 remaining in logs array after the query runs, but all three are remaining currently.
document
{
"_id" : "0jYHGDtEIaE3BCjBW",
"owner" : "a",
"logs" : [
{
"job" : "1",
"createdAt" : "2020-01-31T05:07:09.468Z"
},
{
"job" : "2",
"createdAt" : "2020-01-31T05:07:11.119Z"
},
{
"job" : "3",
"createdAt" : "2021-04-01T05:07:11.119Z"
}
]
}
code
let deleteDate = new Date(Date.now() - 60 * 24 * 60 * 60 * 1000);
Logs.update(
{},
{
$pull: {
logs: {
createdAt: {
$gte: deleteDate,
},
},
},
},
{ multi: true }
);
expected result
{
"_id" : "0jYHGDtEIaE3BCjBW",
"owner" : "a",
"logs" : [
{
"job" : "3",
"createdAt" : "2021-04-01T05:07:11.119Z"
}
]
}
Upvotes: 0
Views: 81
Reputation: 36144
There are few fixes,
createdAt
type is string in collection and new Date
will return date type so condition will always false, you have to change same type in both side either its string or date,toISOString()
after new Date
function to convert date type to string$gte
, it should be $lte
Your final query would be,
let deleteDate = new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString();
Logs.update(
{},
{
$pull: {
logs: {
createdAt: {
$lte: deleteDate
}
}
}
},
{ multi: true }
);
Upvotes: 2