Reputation: 157
I have a MongoDB collection where the last 4 documents look like this:
{'_id': ObjectId('60eb507f9b35c6271434be28'),
'user_id': '123',
'name': 'abc',
'weight': 80}
{'_id': ObjectId('60eb507f9b35c6271434be29'),
'user_id': '123',
'name': 'abc',
'weight': 75}
{'_id': ObjectId('60eb507f9b35c6271434be30'),
'user_id': '789',
'name': 'ghi',
'weight': 88}
{'_id': ObjectId('60eb507f9b35c6271434be31'),
'user_id': '123',
'name': 'abc',
'weight': 80}
Using Pymongo, I want to get a list, that will contain the last 3(most recent) "weight" values of the user_id="123" and name="abc" of my collection. In the above case, the wanted result would be
[80,75,80]
I think one condition in my query would be:
{"$match": {"$and" : [{"user_id": "123"},{"name": abc}]}}
but i am not sure about the rest.
Thank you in advance.
Upvotes: 0
Views: 219
Reputation: 756
If you have timestamp value stored in tr_timestamp
then you can use .sort()
and .limit()
to get you expected output like this:
db.collection.find({
"user_id": "123"
}).sort({
"tr_timestamp": -1
}).limit(3)
If you still want to use the aggregate
pipeline then your query will look like this
db.collection.aggregate([
{
"$match": {
"user_id": "123",
"name": "abc"
}
},
{
"$sort": {
"tr_timestamp": -1
}
},
{
"$limit": 3
}
])
Here is the link to the playground to test your use-case: Mongo Playground
Also, In $match
stage there is no need to combine query explicitly in $and as by default behaviour will be the same as $and only so I have removed that part in my query
OR
If you just want a list of weights then your query will look like this:
db.collection.aggregate([
{
"$match": {
"user_id": "123"
}
},
{
"$sort": {
"tr_timestamp": -1
}
},
{
"$limit": 3
},
{
"$group": {
"_id": "$user_id",
"weights": {
"$push": "$weight"
}
}
}
])
Here is the link to the playground to test your use-case: Mongo Playground
Upvotes: 1