I'm trying to build a query that returns the number of days from a query in mongo. The query would be in just one column called "Date created".
In the filter I need to get the number of days from my query, for example:
Collection:
{
"created_at":"2022-01-02T00:00:00",
"type":"car"
},
{
"created_at":"2022-01-05T00:00:00",
"type":"car"
},
{
"created_at":"2022-01-10T00:00:00",
"type":"car"
}
Query:
db.pipe.aggregate([
{
"$match": {
"created_at": {
"$gte": ISODate("2022-01-01"),
"$lte": ISODate("2022-01-22")
}
}
},
{
"$project": {
"total_days_date_filter": 20,
"total_result_query": 2
}
}
])
result:
{
"total_days_date_filter": 20,
"total_result_query": 2
}
CodePudding user response:
Maybe something like this:
db.collection.aggregate([
{
$project: {
type: 1,
created_at: {
$dateFromString: {
dateString: "$created_at"
}
}
}
},
{
"$match": {
"created_at": {
"$gte": ISODate("2022-01-01"),
"$lte": ISODate("2022-01-22")
}
}
},
{
$group: {
_id: "total",
totalq: {
$sum: 1
},
maxd: {
$max: "$created_at"
},
mind: {
$min: "$created_at"
}
}
},
{
$project: {
_id: 0,
total_result_query: {
$toInt: "$totalq"
},
total_days_day_filter: {
$toInt: {
$dateDiff: {
startDate: "$mind",
endDate: "$maxd",
unit: "day"
}
}
}
}
}
])
