[英]Join array field of objectid with filter and limit - MongoDB
Does anyone know how to get the desired result below with some requirements? 有谁知道如何在一些要求下得到所需的结果? I can't think of much efficient way and hoping that experts can help me. 我想不出有效的方法,希望专家可以帮助我。 :) :)
Thank you very much in advance. 非常感谢你提前。
Playlist Document 播放列表文档
"_id" : "playlist1", "title" : "Sample Playlist",
"items" : ["item3", "item2", "item1", "item5", "item4"] // These are ObjectId type
Items Collection 物品收藏
{ "_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
Page 1: 第1页:
{ "_id" : "item3", "type" : "video", "playlist": "playlist1" } // Maintain order
{ "_id" : "item1", "type" : "video", "playlist": "playlist1" }
Page 2: 第2页:
{ "_id" : "item5", "type" : "video", "playlist": "playlist1" }
This seems to work for me: 这似乎对我有用:
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]}}}
])
you can use $sort $skip $limit of mongodb to get the desired object 你可以使用$ 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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.