【问题标题】:mongoose Date comparing without time and Group by multiple properties?猫鼬日期比较没有时间和按多个属性分组?
【发布时间】:2021-01-03 04:13:43
【问题描述】:

可能问题看起来像重复但为此道歉。因为我们的业务案例与现有问题不同。

我们正在使用 NodejsMongoDB 来编写 REST API。

我有一个名为 EMPLog 的集合,其中包含以下文档对象。

{
    "_id" : ObjectId("5f351f3d9d90b1281c44c5dp"),
    "staffId" : 12345,
    "category" : "trend",
    "page_route" : "http://example.com/rer",
    "expireAt" : ISODate("2020-08-13T11:08:45.196Z"),
    "createdAt" : ISODate("2020-08-13T11:08:45.199Z"),
    "updatedAt" : ISODate("2020-08-13T11:08:45.199Z"),
    "__v" : 0
}
{
    "_id" : ObjectId("5f351f3d9d90b1281c44c5de"),
    "staffId" : 12346,
    "category" : "incident",
    "page_route" : "http://example.com/rergfhfhf",
    "expireAt" : ISODate("2020-08-12T11:08:45.196Z"),
    "createdAt" : ISODate("2020-08-12T11:08:45.199Z"),
    "updatedAt" : ISODate("2020-08-12T11:08:45.199Z"),
    "__v" : 0
}
{
    "_id" : ObjectId("5f351f3d9d90b1281c44c5dc"),
    "staffId" : 12347,
    "category" : "trend",
    "page_route" : "http://example.com/rerrwe",
    "expireAt" : ISODate("2020-08-13T11:08:45.196Z"),
    "createdAt" : ISODate("2020-08-13T11:08:45.199Z"),
    "updatedAt" : ISODate("2020-08-13T11:08:45.199Z"),
    "__v" : 0
}
{
    "_id" : ObjectId("5f351f3d9d90b1281c44c5dr"),
    "staffId" : 12348,
    "category" : "trend",
    "page_route" : "http://example.com/rerrwe",
    "expireAt" : ISODate("2020-08-12T11:08:45.196Z"),
    "createdAt" : ISODate("2020-08-12T11:08:45.199Z"),
    "updatedAt" : ISODate("2020-08-12T11:08:45.199Z"),
    "__v" : 0
}

我们正在接收来自用户的 categorycreatedAt 输入。 createdAt 正在接收没有时间。

假设,用户提供的类别为 trend,createAt 为 2020-08-13,那么我们必须按 trend 分组,createdAt 和 staffId 并将 staffId 作为数组返回。

注意:CategoryCreatedAt 将接收来自用户的动态/运行时。

预期结果是:{data:{staffIds:[12345,12347]}}

如果有人可以指导我,那将是很大的帮助。

在此先感谢所有专家。

【问题讨论】:

  • 你好,staffIds是分类!
  • 您好!听起来您正在尝试使用 createdAt 字段过滤掉 EMPLog 文档,而不考虑日期值的时间分量,对吗?
  • @ChouaibSeghier 你说的是预期结果键“staffIds”吗?
  • @Tunmee 是 CreatedAt 和 category 字段匹配以及 category,staffId 的分组

标签: node.js mongodb express mongoose aggregation-framework


【解决方案1】:

你可以尝试使用$match匹配给定的categorycreatedAt-date,然后分组,最后使用$addToSet得到所有唯一的staffIds:

db.collection.aggregate([
  {
    $match: {
      "category": "trend",
      "createdAt": {$gte: new Date("2020-08-13T00:00:00Z"), $lt: ISODate("2020-08-14T00:00:00Z")}
    }
  },
  {
    "$group": {
      "_id": null,
      "staffIds": {
        "$addToSet": "$staffId"
      }
    }
  }
]);

这是 mongoplayground 上的示例(必须使用字符串和正则表达式作为日期,因为 ISODate 不支持):https://mongoplayground.net/p/oGM7cfvCRQx

【讨论】:

  • 如果我添加相同日期的相同staffId,那么它将返回重复的staffId。所以我们如何对 staffId 进行分组,这样它就不会在同一日期返回重复的 staffId
  • 你可以用$addToSet代替$push :)
  • 非常感谢。你拯救了我的一天。对 mongodb 有很大帮助
猜你喜欢
  • 2016-10-01
  • 2017-04-29
  • 2021-03-24
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 2016-04-08
  • 2012-07-22
  • 2020-10-02
相关资源
最近更新 更多