【问题标题】:$fitler nested array using $lte $gte$filter 嵌套数组使用 $lte $gte
【发布时间】:2019-06-27 22:15:11
【问题描述】:

我正在使用 Mongoose 和 MongoDB 实现一个带有“用户”文档的后端,例如:

> db.users.find().pretty()
{
        "_id" : ObjectId("5c46eb642c825626124b1e3c"),
        "username" : "admin",
        "searches" : [
                ISODate("2019-01-30T14:52:07Z"),
                ISODate("2019-01-30T14:53:40Z"),
                ISODate("2019-01-30T14:54:48Z"),
                ISODate("2019-02-03T17:11:57Z"),
                ISODate("2019-02-04T06:40:00Z")
        ]
}

搜索字段是一个数组,记录用户运行某些搜索功能的时间。我想选择一个用户名并计算在过去一小时、一天和总共运行了多少次搜索。我的问题是在一个查询中获取这三个值。

我正在使用聚合来选择用户,通过展开提取搜索,按时查询,例如日期大于一小时前,并计算结果。

>let now = new Date()
ISODate("2019-02-04T06:56:29.095Z")
>let onehourago = new Date(now.getTime() - 1000 * 3600);
>let yesterday = new Date(now.getTime() - 1000 * 3600 * 24);
>let queryUser = { $match: {username: "admin"}};
>let unwind = { $unwind : "$searches" };
>let queryTime = { $match: {searches: {$gte: onehourago}}};
>let counter = {$count: "lasthour"};
>db.users.aggregate([queryUser, unwind, queryTime, counter])
{ "lasthour" : 1 }

我想得到:

{ "lasthour" : 1, "today": 2, "total": 5 }

如果在没有匹配项时查询返回 0 而不是空,则奖励积分(但我可以在 javascript 中解决这个问题)。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    可以使用$filter聚合过滤掉searches数组

    db.collection.aggregate([
      { "$match": { "username": "admin" }},
      { "$project": {
        "total": { "$size": "$searches" },
        "lasthour": {
          "$size": {
            "$filter": {
              "input": "$searches",
              "as": "search",
              "cond": {
                "$and": [
                  { "$gte": ["$$search", onehourago] },
                  { "$lte": ["$$search", now] }
                ]
              }
            }
          }
        },
        "today": {
          "$size": {
            "$filter": {
              "input": "$searches",
              "as": "search",
              "cond": {
                "$and": [
                  { "$gte": ["$$search", yesterday] },
                  { "$lte": ["$$search", now] }
                ]
              }
            }
          }
        }
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 2019-05-14
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 2022-12-05
      • 2016-11-17
      相关资源
      最近更新 更多