从索引到末尾获取数组元素。

huangapple go评论69阅读模式
英文:

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' }]  } } }
)

huangapple
  • 本文由 发表于 2020年1月3日 17:24:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定