Reputation: 11
i have list of documents like this
"Location_id": "60b53d92ccb1483964da45f9",
"SensorIdentifier": "CCCCCCCCCCCCCCCC",
"SensorType": "Temperature",
"status": true,
"data": [
{
"temperature": 22.5,
"humidite": 38.2,
"batterie": 50,
"time": 1623083627736,
"date": "7-6-2021"
},
i want to filter them by date for example i want to get documents where date between 6-6-2021 and 7-6-2021 with filtering the subdocument in data array, note that date field is string ,now here is my solution:
{
"$match": {
"$expr": {
"$and": [
{
"$gte": [
"$date",
{
"$dateFromString": {
"dateString": "4-6-2021",
"format": "%m-%d-%Y"
}
}
]
},
{
"$lte": [
"$date",
{
"$dateFromString": {
"dateString": "7-6-2021",
"format": "%m-%d-%Y"
}
}
]
}
]
}
}
},
Upvotes: 1
Views: 53
Reputation: 20304
You can do it like this:
db.collection.aggregate([
{
"$match": {
"Location_id": "60b53d92ccb1483964da45f9"
}
},
{
"$set": {
"data": {
"$filter": {
"input": "$data",
"cond": {
"$and": [
{
"$lte": [
{
"$dateFromString": {
dateString: "$$this.date",
format: "%m-%d-%Y"
}
},
{
"$dateFromString": {
dateString: "7-6-2021",
format: "%m-%d-%Y"
}
}
]
},
{
"$gte": [
{
"$dateFromString": {
dateString: "$$this.date",
format: "%m-%d-%Y"
}
},
{
"$dateFromString": {
dateString: "4-6-2021",
format: "%m-%d-%Y"
}
}
]
}
]
}
}
}
}
}
])
Here is the working example: https://mongoplayground.net/p/-l2O6wp9SFV
Upvotes: 1