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.
CodePudding user response:
If you want both values, list them both with a projection like:
{
messages: [
{$slice: ["$messages", 1]},
{$slice: ["$messages",-1],}
],
}
CodePudding user response:
Using aggregate you can use $first and $last like this:
db.collection.aggregate([
{
"$project": {
"first": {
"$first": "$messages"
},
"last": {
"$last": "$messages"
}
}
}
])
Example here