usmansharif shaik
usmansharif shaik

Reputation: 75

finding the document based on mongodb query condition

{
"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

Answers (1)

ray
ray

Reputation: 15276

Storing the field as JSON string is considered as an anti-pattern. Consider storing them as proper BSON objects.

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

Related Questions