1

I want to retrieve only the first and last element from an array in a document, by using the "find" function, without using "aggregate".

Here is a Mongo Playground Link

Consider a document

{
    _id:"1",
    messages:[
        {
            "text":"First item",
        },
        {
            "text":"Middle item",
        },
        {
            "text":"Last item",
        },
    ],
}

So far, I was able to retrieve only the first or last, for example, to get the last item, I am doing:

messages: {
    $slice: ["$messages", -1], //Get the last element
},

How can I get both the first (0th index) and the last (nth index) at the same time?

Note: I do not have any information about the length of the array from beforehand.

Note 2: The reason why I would prefer not using "aggregate" is due to having more filters, selections, limits and other various query properties being handled through the find(), limit(), etc. functions of mongoose, which I am using in a generic way to define my wrapper.

1
  • I can't think of a way without aggregation... What are your other filters? Maybe you can migrate them all to aggregation. Commented Nov 3, 2021 at 7:57

2 Answers 2

3

If you want both values, list them both with a projection like:

{
  messages: [
    {$slice: ["$messages", 1]},
    {$slice: ["$messages",-1],}
  ],
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, this is what I needed.
1

Using aggregate you can use $first and $last like this:

db.collection.aggregate([
  {
    "$project": {
      "first": {
        "$first": "$messages"
      },
      "last": {
        "$last": "$messages"
      }
    }
  }
])

Example here

1 Comment

Thank you. Is it possible to do it by normal find method? I am using various other filters, selections and etc. And in that case it'll be great if I can just modify part of the "select" area, like I am doing in my example playground.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.