skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. the response is not exactly as the format as you want but you can do it with only one sort and a group stage

    test it here

    db.collection.aggregate([
      {
        "$sort": {
          "InsertedAt": 1
        }
      },
      {
        "$group": {
          "_id": null,
          "first": {
            "$first": "$$ROOT"
          },
          "last": {
            "$last": "$$ROOT"
          }
        }
      },
      {
        "$project": {
          _id: 0
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search