英文:
How to get elements from an array from a index to the end
问题
chat = { _id: someid, messages: [{text: 'aaa'}, {text: 'bbb'}, {text: 'ccc'}, {text: 'ddd'}] }
我需要提取从索引1开始到数组的末尾的消息。
谢谢。
迄今为止尝试的代码:
let theIndex = 1;
Model.aggregate(
{ $match: condition },
{ $project: { 'chat': { $slice: ['$chat.messages', theIndex] } } }
)
这将给我25条消息,但我需要它一直到数组的末尾。
希望问题清楚。
英文:
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.
答案1
得分: 1
你可以将 $size
作为最后一个 $slice
参数使用:
let theIndex = 1;
Model.aggregate(
{ $match: condition },
{ $project: { 'chat': { $slice: ['$chat.messages', theIndex, { $size: '$messages' }] } } }
)
英文:
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' }] } } }
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论