首页 > 解决方案 > 如何计算猫鼬中开始日期和结束日期的总时间?

问题描述

我们的用户模式是这样的......

const docSchema = new mongoose.Schema({
    userType: {
        type: String,
        enum: [
            'customer',
            'driver'
        ]
    },
    userId: {
        type: String,
        refPath: 'userType'
    },
    device: {
        type: String,
        enum: [
            'Android',
            'IOS'
        ]
    },
    appVersion: {
        type: String,
        default: ''
    },
    deviceId: {
        type: String,
        default: ''
    },
    connected: {
        type: Date,
        default: ''
    },
    disconnected: {
        type: Date,
        default: ''
    }
}, {
        timestamps: true
    });

现在,我们必须计算用户使用连接和断开连接的总在线时间,任何人都可以帮助我们如何实现这一点?

标签: node.jsmongoose

解决方案


从您的问题来看,似乎对于每个会话(即一个连接和断开连接),您正在为DocSchema[让,调用模型DocSchema]中的用户创建一个文档。你想知道一个用户的总时间。您可以使用aggregate.

这是一个aggregation查找 userId 总时间的示例searchKey

Schema2.aggregate({
  $match: {
    userId: searchKey,
    $project: {
      diff: {
        $subtract: ['$disconnected', '$connected']
      }
    },
    $group: {
      _id: 'justAGroupName',
      total: {
        $sum: '$diff'
      }
    }
  }
});

有关更多信息,请查看mongodb 聚合文档


推荐阅读