Suraj
Suraj

Reputation: 25

How to get elements from an array from a index to the end

Sample Mongo Document

chat = { _id: someid, messages: [{text: 'aaa'}, {text: 'bbb'}, {text: 'ccc'}, {text: 'ddd'}] }

I need to extract messages starting from index 1 till the end of the array. Thanks.

Codes tried so far:

let theIndex = 1;
Model.aggregate(
  { $match: condition },
  { $project: { 'chat': { $slice: ['$chat.messages', theIndex, 25]  } } }
)

This will give me 25 messages, but i need it to be till the end of the array.

Hope the question is clear.

Upvotes: 1

Views: 37

Answers (1)

mickl
mickl

Reputation: 49945

You can just use $size as a last $slice parameter:

let theIndex = 1;
Model.aggregate(
   { $match: condition },
   { $project: { 'chat': { $slice: ['$chat.messages', theIndex, { $size: '$messages' }]  } } }
)

Upvotes: 1

Related Questions