Reputation: 75
{
"responseType" : "success",
"sentPayload" : "{\"regId\":\"AR34JK\",\"createdOn\":\"2021-12-16T11:17:28.640Z\"}",
"sentUrl" : "DB",
"tat" : 38.044
}
This is my JSON. how to write a MongoDB query based on the sentPayload.createdOn
condition?
i have written query {"sentPayload.createdOn":{$gte:new Date("2021-12-16")}}
but this is not returning the document.pls help me
Upvotes: 0
Views: 113
Reputation: 15276
Nevertheless, starting with MongoDB v4.4+, you can use $function
to do a javascript JSON.parse
to convert the JSON string back to JSON object. Then do a $toDate
to convert the createdOn
field back to proper date field.
db.collection.aggregate([
{
$addFields: {
sentPayload: {
$function: {
body: "function(sentPayload) {return JSON.parse(sentPayload)}",
args: [
"$sentPayload"
],
lang: "js"
}
}
}
},
{
$addFields: {
"sentPayload.createdOn": {
$toDate: "$sentPayload.createdOn"
}
}
},
{
$match: {
"sentPayload.createdOn": {
$gte: ISODate("2021-12-16T00:00:00.000Z")
}
}
}
])
Here is the Mongo playground for your reference.
Upvotes: 1