简体   繁体   中英

How to find data in for every day of week in mongoose node js

Query

const weekGraph = await tmUserSubscriptions.aggregate([
            {
                $match:{$and:[{subscriptionId: mongoose.Types.ObjectId(subscriptionId)},
                {createdAt:{$gte:moment().startOf('isoweek').toDate(),
                 $lt:moment().endOf('isoweek').toDate()}}
                ]}
            },
            {"$project":{
                "_id:":1,
                "createdAt":{"$dayOfWeek":"$createdAt"},
                "subscriptionId":1,
                
        }},
        {"$group":{
            "_id":"$createdAt",
            "count":{$sum:1},
        }}
        ])

Result i get

"data": [
        {
            "_id": 7,
            "count": 1
        },
        {
            "_id": 5,
            "count": 2
        },
        {
            "_id": 6,
            "count": 1
        }
    ]

expected Result

"data": [
        {
            "_id": 7,
            "count": 1
        },
        {
            "_id": 6,
            "count": 2
        },
        {
            "_id": 5,
            "count": 1
        },
        {
            "_id": 4,
            "count": 0
        },{
            "_id": 3,
            "count": 0
        },{
            "_id": 2,
            "count": 0
        }{
            "_id": 1,
            "count": 0
        }
    ]

So here i want to achieve all data of current week day by day, in my current query if there is no data any of week day then it will not return that day, but as per my expected result i want all day of week data, if there is no data for any of week day then it will return 0, so i want all 7 days data, here _id is represent day of week

Mongoose/MongoDB will only return the aggregate if the key exists. Otherwise, it will not return you the data (less data to transfer through the connection is always faster). Therefore, you will need to provide your own defaults if the aggregate does not have data for you.

var results = [{ _id: 1, count: 1 }] // assumed from your response

var hasResult = []
for (var result of results) {
  hasResult.push(result._id)
}

for (var i = 1; i <= 7; i++) {
  if (!hasResult.includes(i)) {
    results.push({ _id: i, count: 0 })
  }
}

console.log(results)

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