使用filter和limit连接objectid的数组字段 - MongoDB

时间:2017-04-19 08:12:55

标签: arrays mongodb mongodb-query

有谁知道如何在某些要求下获得所需的结果?我想不出有效的方法,希望专家可以帮助我。 :)

非常感谢你。

播放列表文件

"_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

要求

  • 使用跳过
  • 限制为 2
  • 仅限视频
  • 的类型
  • 按播放列表文档中的项目数组字段维护订单
  • 高效的方式,因为物品可以是巨大的阵列(如1000 +)

期望结果

第1页:

{ "_id" : "item3", "type" : "video", "playlist": "playlist1" } // Maintain order
{ "_id" : "item1", "type" : "video", "playlist": "playlist1" }

第2页:

{ "_id" : "item5", "type" : "video", "playlist": "playlist1" }

2 个答案:

答案 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
        });