【问题标题】:How to use aggregation operation of mongoDB in JSON data [duplicate]如何在JSON数据中使用mongoDB的聚合操作[重复]
【发布时间】:2017-09-21 17:46:40
【问题描述】:

假设这是一个输入 JSON 数据并且集合名称是地点。

  [
    {
        "time": ISODate("2016-11-27T011:43:01.000+05:30"), 'userId': 'abc'
    },
    {
        "time": ISODate("2016-11-28T01:43:01.000+05:30"),'userId': 'pqr'
    },
    {
        "time": ISODate("2016-11-27T08:43:01.000+05:30"), 'userId': 'abc'
    },
    {
        "time": ISODate("2016-11-27T02:43:01.000+05:30"), 'userId': 'abc'
    },
    {
        "time": ISODate("2016-11-27T011:43:01.000+05:30"), 'userId': 'pqr'
    },
    {
        "time": ISODate("2016-11-28T011:43:01.000+05:30"), 'userId': 'abc'
    }
]

在上面给出的 JSON 数据中,我们在一个集合中维护了用户日志。当用户第一次登录时,我们必须找出与日期相对应的数据。我们必须对这个 json 数据执行操作,以便输出应该是这种格式。

输出

[{"date": "2016-11-27",
  'user': [{'userId':'abc','time': ISODate("2016-11-27T08:43:01.000+05:30")},
            'userId':'pqr','time': ISODate("2016-11-27T11:43:01.000+05:30")]
 },
 {"date": "2016-11-28",
  'user': [{'userId':'abc','time': ISODate("2016-11-28T11:43:01.000+05:30")},
            'userId':'pqr','time': ISODate("2016-11-28T1:43:01.000+05:30")]
 }]

【问题讨论】:

  • @Guys!请不要专注于日期格式。您可以以任何格式打印

标签: node.js mongodb mongoose aggregation-framework


【解决方案1】:

您可以尝试以下聚合查询。

db.collection_name.aggregate([
  {
    "$sort": {
      "userId": 1,
      "time": -1
    }
  },
  {
    "$group": {
      "_id": {
        "date": {
          "$dateToString": {
            "format": "%Y-%m-%d",
            "date": "$time"
          }
        },
        "userId": "$userId"
      },
      "time": {
        "$first": "$time"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "user": {
        "$push": {
          "userId": "$_id.userId",
          "time": "$time"
        }
      }
    }
  },
  {
    "$sort": {
      "_id": 1
    }
  }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2021-11-03
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多