search

Home  >  Q&A  >  body text

mongodb - How to query the maximum value of updateAt in each userId

{
    userId: OjbectId,
    updatedAt: Date
}

I am a newbie, please give me some advice.

阿神阿神2792 days ago616

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