代码之家  ›  专栏  ›  技术社区  ›  kecman

Mongoose-在集合中未找到任何内容时,对其进行分组、计数并返回0

  •  2
  • kecman  · 技术社区  · 6 年前

    我的mongoDB数据库中有两个集合- users connections . 每个 connection 有字段 user 其中包含 _id 一个 用户 储存在 用户 收藏。

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

    还要查找连接数 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'
        }
    

    用户架构:

    local: {
            email: String,
            password: String,
            admin: Boolean,
            snoozeAmount: Number,
            snoozeInterval: String,
            emailIntervalWeeks: Number,
            emailIntervalDay: Number,
            isVerified: { type: Boolean, default: false },
            verifyToken: String,
            passwordResetToken: String,
            lastConnectionEdit: Date
        }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Ashh    6 年前

    您可以尝试以下聚合

    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 }
                }}
              ]
            }
          }
        }
      }}
    ])