有谁知道如何在某些要求下获得所需的结果?我想不出有效的方法,希望专家可以帮助我。 :)
非常感谢你。
播放列表文件
"_id" : "playlist1", "title" : "Sample Playlist",
"items" : ["item3", "item2", "item1", "item5", "item4"] // These are ObjectId type
项目集合
{ "_id" : "item1", "type" : "video", "playlist": "playlist1" }
{ "_id" : "item2", "type" : "music", "playlist": "playlist1" }
{ "_id" : "item3", "type" : "video", "playlist": "playlist1" }
{ "_id" : "item4", "type" : "music", "playlist": "playlist1" }
{ "_id" : "item5", "type" : "video", "playlist": "playlist1" }
{ "_id" : "item6", "type" : "video", "playlist": "playlist2" } // Different playlist
第1页:
{ "_id" : "item3", "type" : "video", "playlist": "playlist1" } // Maintain order
{ "_id" : "item1", "type" : "video", "playlist": "playlist1" }
第2页:
{ "_id" : "item5", "type" : "video", "playlist": "playlist1" }
答案 0 :(得分:1)
这似乎对我有用:
db.test.aggregate([
{$match: {_id: "playlist1"}},
{$unwind: {path: "$items", includeArrayIndex: 'item_index'}},
{$limit: 2},
{
$lookup: {
from: "items",
localField: "items",
foreignField: "_id",
as: "items"
}
},
{$sort: {item_index: 1}},
{$replaceRoot: {newRoot: {$arrayElemAt: ["$items", 0]}}}
])
答案 1 :(得分:-1)
您可以使用$ sort $ skip $ limit of mongodb来获取所需的对象
db.Items.aggregate({
$match: {"type":"video"}
}, {
$sort: {
KEY_TO_SORT: -1
}
}, {
$skip: parseInt(skip)
}, {
$limit: parseInt(limit)
},
function (err, success) {
// Error and success comes here
});