I have a photo collection which stores the user, tag, date and photo url. I want a query to return the 2 latest photo for a user per tag.
eg
{user: 1, date: 1, url: a, tag: tag1}
{user: 1, date: 2, url: b, tag: tag1}
{user: 1, date: 3, url: c, tag: tag1}
{user: 1, date: 4, url: d, tag: tag2}
{user: 2, date: 1, url: e, tag: tag1}
{user: 3, date: 1, url: f, tag: tag1}
Running the query on user 1 should return
{user: 1, date: 1, url: a, tag: tag1}
{user: 1, date: 2, url: b, tag: tag1}
{user: 1, date: 4, url: d, tag: tag2}
I am using mongoose with NodeJs.
Query
$setWindowFields
*alternative solution for MongoDB <5 would be to sort by date, group by tag, and slice to get only the first 2.
aggregate(
[{"$match":{"$user" : 1}},
{"$setWindowFields":
{"partitionBy":"$tag",
"sortBy":{"date":1},
"output":{"rank":{"$rank":{}}}}},
{"$match":{"$expr":{"$lt":["$rank", 3]}}},
{"$unset":["rank"]}])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.