我的数据库如下:
{email:"user", contacts:
[
{emailContact:"test", firstName:"test", lastName:"test", messages:
[
{email:"user", content:"hi", date:"ISODate(...)"}
{email:"test", content:"how are you?", date:"ISODate(...)"}
{email:"user", content:"im fine", date:"ISODate(...)"}
]
},
{emailContact:test2, firstName:"test2", lastName:"test2", messages:
[
{email:"user", content:"hahaha", date:"ISODate(...)"}
{email:"test2", content:"yea thats right", date:"ISODate(...)"}
{email:"user", content:"xd", date:"ISODate(...)"}
]
}
]
}
我需要从具有给定联系人的特定用户那里获得2条最新消息。
我已经尝试了几种类似的方法:
db.contacts.aggregate([{$match:{email:"user",emailContact:"test"}},{$unwind:{'contacts.messages'}},{$sort:{'contacts.messages.date':1,'contacts.messages.content':1,'contacts.messages.emailContact':1}},{$group:{who:'$email', content:'$content', date:{$last:'$date'}}}])
谢谢您的帮助
答案 0 :(得分:0)
双重$unwind
可以做到。
db.contacts.aggregate([
{$match: {email: 'user'}},
{$unwind: '$contacts'},
{$match: {'contacts.emailContact': 'test'}},
{$unwind: '$contacts.messages'},
{$sort: {'contacts.messages.date': -1}},
{$limit: 2},
{$replaceRoot: {newRoot: '$contacts.messages'}}
])