简体   繁体   English

如何在 mongoose 节点 js 中查找一周中每一天的数据

[英]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所以在这里我想每天获得当前一周的所有数据,在我当前的查询中,如果工作日没有任何数据,那么它将不会返回那一天,但根据我的预期结果,我想要一周中的所有数据,如果工作日的任何一天都没有数据,那么它将返回 0,所以我想要所有 7 天的数据,这里 _id 代表星期几

Mongoose/MongoDB will only return the aggregate if the key exists.如果键存在,Mongoose/MongoDB 只会返回聚合。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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