猫鼬-分组,计数并在集合中未找到任何内容时返回0

时间:2018-08-04 23:51:52

标签: javascript node.js mongodb mongoose

我的mongoDB数据库中有2个集合-usersconnections。 每个connection的字段user包含_id集合中存储的user的{​​{1}}。

我需要找到每个用户的连接总数,如果用户没有连接,则应显示0作为其总数。

还要查找每个用户的users字段不等于date的连接数。

我编写了这段代码,可以重新计算每个用户的连接总数,但是仅对于具有至少一个连接的用户,没有连接的用户根本不会显示...

''

连接模式:

Connection.aggregate(
                [
                    {
                        $group: {
                            _id: "$user",
                            total: { $sum: 1 },
                            withDate: { $sum: { $cond: { if: { $ne: ["$date", ""] }, then: 1, else: 0 } } }
                        }
                    },
                    {
                        $lookup: {
                            from: "users",
                            localField: "_id",
                            foreignField: "_id",
                            as: "users"
                        }
                    },
                    {
                        $unwind: "$users"
                    },
                    {
                        $project: {
                            Email: "$users.local.email",
                            "Last Edit": { $dateToString: { format: "%Y-%m-%d", date: "$users.local.lastConnectionEdit" } },
                            "Total Connections": "$total",
                            "Connections With Date": "$withDate"
                        }
                    }
                ],
                function(err, dashboardData) {
                    if (err) {
                        console.log(err);
                        res.status(500).end({ error: "Error fetching stats from database" });
                    } else {
                        let csv = json2csv(dashboardData);

                        res.attachment("stats.csv");
                        res.status(200).send(csv);
                    }
                }
            );

用户架构:

    active:Boolean,
    info: {
        name: String,
        profileImg: String,
        bio: String
    },
    connURL:String,
    handle:String,
    notes: String,
    date: String,
    value: {
        type: Number,
        min: 0,
        max: 5
    },
    tags: [String],
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }

1 个答案:

答案 0 :(得分:2)

您可以尝试以下汇总

User.aggregate([
  { "$lookup": {
    "from": "connections",
    "localField": "_id",
    "foreignField": "user",
    "as": "connections"
  }},
  { "$addFields": {
    "total": { "$size": "$connections" },
    "withDate": {
      "$reduce": {
        "input": "$connections",
        "initialValue": 0,
        "in": {
          "$add": [
            "$$value",
            { "$sum": {
              "$cond": { "if": { "$ne": [ "$$this.date", "" ] }, "then": 1, "else": 0 }
            }}
          ]
        }
      }
    }
  }}
])