search

Home  >  Q&A  >  body text

mongodb - 怎么查询每个userId中updateAt最大的值

{
    userId: OjbectId,
    updatedAt: Date
}

本人菜鸟,求教一下.

阿神阿神2757 days ago582

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-05-02 09:25:01

    If you know how to write it in SQL, the same principle applies to MongoDB. This is a very common grouped aggregation query. The answers are below, but I still hope you can try to search for the answers online and exercise your ability to solve problems independently.

    db.collection.aggregate([
      {$group: {_id: "$userId", maxUpdatedAt: {$max: "$updatedAt"}}}
    ]);

    The answer can be easily obtained using aggregation’s $max operator.

    reply
    0
  • Cancelreply