简体   繁体   English

$limit 和 $skip 在 MongoDB 聚合管道中作为可选

[英]$limit and $skip as optional in MongoDB Aggregation pipeline

I have a pipeline with $facet and using pagination inside it with $skip and $limit .我有一个带有$facet的管道,并在其中使用$skip$limit的分页。 I want to implement a condition when parameters are passed to skip and limit then only pagination should work else it should return me all the records.我想在传递参数以跳过和限制时实现一个条件,然后只有分页应该起作用,否则它应该返回所有记录。

Model.aggregate([
    {
      $facet: {
        comments: [
          {
            $match: { issueId: Types.ObjectId(issueId) },
          },
          {
            $skip: skip,
          },
          {
            $limit: parseInt(size, 10),
          },
          {
            $lookup: {
              from: 'users',
              localField: 'createdBy',
              foreignField: '_id',
              as: 'commentedBy',
            },
          },
        ]
      }
    }
]

Try separating all pipeline on the base of condition,尝试根据条件分离所有管道,

let pagination = true; // true for add, false for remove 
// initialise default comments array
let comments = [];

// set match stage
comments.push({  $match: { issueId: Types.ObjectId(issueId) } });

// if pagination is required, put you condition to enable disable pagination
if (pagination === true) {
  comments.push({ $skip: skip });
  comments.push({ $limit: parseInt(size, 10) });
}

// lookup
comments.push({
  $lookup: {
    from: 'users',
    localField: 'createdBy',
    foreignField: '_id',
    as: 'commentedBy',
  },
});

// execute query
Model.aggregate([{ $facet: { comments: comments } }]);

Second option using concat array function Array.prototype.concat ,第二个选项使用 concat 数组 function Array.prototype.concat

let pagination = true; // true for add, false for remove 
Model.aggregate([
  { 
    $facet: Array.prototype.concat(
      [{  $match: { issueId: Types.ObjectId(issueId) } }],
      ( 
        pagination == true ? [{ $skip: skip }, { $limit: parseInt(size, 10) }] : []
      ),
      [{
        $lookup: {
          from: 'users',
          localField: 'createdBy',
          foreignField: '_id',
          as: 'commentedBy',
        }
      }]
    )
  }
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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