实际上,如果您使用的 mongoDB 版本低于 3.1.6,则使用单个查询是不可能的。
mongoDB version 3.1.6 and above 中的聚合管道支持$Slice
如果您的 mongoDB 版本低于 3.1.6,那么您可以尝试以下代码:
db.collection.aggregate([
{ $unwind : "conversations"},
{ $sort : {_id : 1, conversations.date : -1}},
{ $group: { _id : "$_id"} , conversations : { $push : "$conversations"}, participants : {$first : "$participants"} },
{ $project : { _id : 1, conversations : 1, participants : 1 } }
]).forEach( function(doc)
{
if( doc.conversations.length > 6)
{
var count = doc.conversations.length - 6;
doc.conversations.splice(6, count );
}
}
)
3.1.6以下版本的StackOverflow上有类似的问题,请查看the link。
对于mongoDb Version 3.1.6 and above,可以在聚合管道中使用$Slice来限制数组的内容。
试试下面的代码:
db.collection.aggregate([
{ $unwind : "conversations"},
{ $sort : {_id : 1, conversations.date : -1}},
{ $group: { _id : "$_id"} , conversations : { $push : "$conversations"}, participants : {$first : "$participants"} },
{ $project :
{
_id : 1,
participants : 1,
newconversations :
{
conversations : { $slice : 6 }
}
}
}
])