EN VI

How can I get the first and the last element from MongoDB collection?

2024-03-15 22:00:06
How can I get the first and the last element from MongoDB collection?

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?

Solution:

Just chain up your 2 queries with $unionWith

db.collection.aggregate([
  {
    "$sort": {
      "insertedAt": 1
    }
  },
  {
    $limit: 1
  },
  {
    "$unionWith": {
      "coll": "collection",
      "pipeline": [
        {
          "$sort": {
            "insertedAt": -1
          }
        },
        {
          $limit: 1
        }
      ]
    }
  }
])

Mongo Playground

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login