0
我目前正在嘗試使用子元素的最後日期對MongoDB中的集合進行排序。MongoDB - 按子集合中的最新日期排序
看來我應該使用.aggregate函數,但似乎無法將其整理出來。
數據的結構
{
_id: int,
cellNumber: string
messages: [
{
_id: int,
body: string,
date: Date/Time
}
]
}
它看起來像我應該使用的代碼
db.contacts.aggregate([
{ $group: { _id: "$_id", lastDate: { $last: "$messages.date" } } },
{ $sort: { lastDate: 1 } }
])
但與2名兒童預期元素總是返回2個日期
:
{ _id: parentId, lastDate: dateOfLastMessage }
實際:
{ _id: parentId, lastDate: [ dateOfMessage1, dateOfMessage2 ]}