I have a mongodb collection called "Users" and I want to create a query to get the first and the last document from this collection based in a datetime field called InsertedAt
.
I know how to get the first and the last element using sort
, but I want to return both records in one query, like this:
[
{
_id: ObjectId("65c656fd8651a89640db013a"),
insertedAt: ISODate("2023-02-01T16:46:33.166Z"), // First record of collection
name: "Bob Jhonson"
},
{
_id: ObjectId("65c4d88a2a06618ad4e972f4"),
insertedAt: ISODate("2023-03-11T12:16:33.166Z"), // Last record of collection
name: "Bob Jhonson"
}
]
How can I do this?
2
Answers
Just chain up your 2 queries with
$unionWith
Mongo Playground
the response is not exactly as the format as you want but you can do it with only one
sort
and agroup
stagetest it here