Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use $gte and &lte mongo operator if date is in string format in mongodb

I have dob field like {dob:"02-23-2000"} in database. Now I want to perform $gte and &lte on dob field that is in string format like below:

db.panelists.count({"dob":{ '$gte': '08-02-1998', '$lte': '08-02-2003' }});

I am getting count value as zero always.

Could anyone please help me out to resolve this query in same dob format.

like image 712
Nilesh Kumar Avatar asked Aug 02 '18 06:08

Nilesh Kumar


1 Answers

You can try below aggregation in mongodb 3.6

You can use $dateFromString aggregation to convert your dob from string to date and then easily $count the documents applying $match on it.

1) Using aggregation with $addFields

db.panelists.aggregate([
  { "$addFields": {
    "date": {
      "$dateFromString": { "dateString": "$dob", "format": "%m-%d-%Y" }
    } 
  }},
  { "$match": {
    "date": {
      "$gte": moment('08-02-1998').toDate(),
      "$lte": moment('08-02-2003').toDate()
    }
  }},
  { "$count": "count" }
])

2) Using simple find query with $expr

db.collection.find({
  "$expr": {
    "$and": [
      {
        "$gte": [
          { "$dateFromString": { "dateString": "$dob", "format": "%m-%d-%Y" }},
          ISODate("2000-02-22T00:00:00Z")
        ]
      },
      {
        "$lte": [
          { "$dateFromString": { "dateString": "$dob", "format": "%m-%d-%Y" }},
          ISODate("2000-02-24T00:00:00Z")
        ]
      }
    ]
  }
})

3) Using aggregation with $expr

db.collection.aggregate([
  { "$match": {
    "$expr": {
      "$and": [
        {
          "$gte": [
            { "$dateFromString": { "dateString": "$dob", "format": "%m-%d-%Y" }},
            ISODate("2000-02-22T00:00:00Z")
          ]
        },
        {
          "$lte": [
            { "$dateFromString": { "dateString": "$dob", "format": "%m-%d-%Y" }},
            ISODate("2000-02-24T00:00:00Z")
          ]
        }
      ]
    }
  }}
])
like image 62
Ashh Avatar answered Nov 15 '22 08:11

Ashh