简体   繁体   中英

Mongoose, mongodb, bad aggregate grouping

I m actually trying to get some information concerning my app.

I have to get some informatiogrouping by day / month / year. I have the good result attributes, but information is displayed even if there is nothing in DB.

NB : Start and End are good formatted dates.

TraitementNettoyage.aggregate([
      {$match: { 'dateEntre': {$gt: start}, 'dateEntre': {$lt: end} }},
      {$group: {'_id': {'day': {'$dayOfMonth': '$dateEntre'}, 'month': {'$month': '$dateEntre'}, 'year': {'$year': '$dateEntre'}}, count: {$sum: 1}}}
    ]).exec((err, res)=>
console.log res
)

And I get this resultset :

[
    {
        "_id": {
            "day": 24,
            "month": 3,
            "year": 2015
        },
        "count": 2
    }
]

The fact is that I have nothing in DB concerning the 2015-03-24. In my DB, I have only 2 sets of data with the 2015-03-23 date.

What should I correct in my request to get the exact two resultsets :

[
    {
        "_id": {
            "day": 24,
            "month": 3,
            "year": 2015
        },
        "count": 0
    }
]

and

[
    {
        "_id": {
            "day": 23,
            "month": 3,
            "year": 2015
        },
        "count": 2
    }
]

?

EDIT :

Here the resultset with $lte and $gte :

[
    {
        "_id": {
            "day": 25,
            "month": 3,
            "year": 2015
        },
        "count": 2
    },
    {
        "_id": {
            "day": 24,
            "month": 3,
            "year": 2015
        },
        "count": 2
    }
]

The problem is that the count are not correct. in fact it should be 2 for 24/03/2015 and 0 for 25/03/2015.

Thanks for advance

split the $match for dateEntre

TraitementNettoyage.aggregate([
      {$match: { 'dateEntre': {$gte: start}}},
      {$match: { 'dateEntre':  {$lte: end}}},
      {$group: {'_id': {'day': {'$dayOfMonth': '$dateEntre'}, 'month': {'$month': '$dateEntre'}, 'year': {'$year': '$dateEntre'}}, count: {$sum: 1}}}
    ]).exec((err, res)=>
console.log res
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM