Sorting for particular user in mongodb

Viewed 16

I am trying to get the last record for a particular user id. For example.if user_id 2 has 10 records I need the 10th record.

I have tried for static user_id

Help me to change in dynamic

db.product_logs.find({"user_id" :"862"}).sort({"_id":-1}).limit(1)
1 Answers

You can simply assign a variable to the given user_id and use that in the find query.

For example, in javascript, you can do something like this:

let userId = "862";//assign this variable as per your requirement/choice
db.product_logs.find({"user_id" :userId}).sort({"_id":-1}).limit(1)
Related