I have dob field like {dob:"02-23-2000"} in database. Now I want to perform $gte and <e 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.
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")
]
}
]
}
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With