简体   繁体   English

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

[英]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

Requirements 要求

  • Limit to 2 with skip 跳过限制为2
  • Only type of video 只有视频类型
  • Maintain order as in items array field in playlist document 维护播放列表文档中的项目数组字段中的顺序
  • Efficient way as items can be huge array (like 1000+) 高效的方式,因为项目可以是巨大的阵列(如1000+)

Desired Result 期望的结果

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM