node.js - $limit 和 $skip 在 MongoDB 聚合管道中作为可选

标签 node.js database mongodb mongoose aggregation-framework

我有一个带有 $facet 的管道,并在其中使用 $skip$limit 进行分页。我想在参数传递给skip和limit时实现一个条件,那么只有分页应该起作用,否则它应该返回所有记录。

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

最佳答案

尝试根据条件分离所有管道,

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 } }]);

使用 concat 数组函数的第二个选项 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',
        }
      }]
    )
  }
]);

关于node.js - $limit 和 $skip 在 MongoDB 聚合管道中作为可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67373807/

相关文章:

javascript - 通过node js上传到dropbox失败

javascript - 使用 InversifyJS 注入(inject)函数的最佳方法

node.js - 尝试创建 Vue 应用程序,但在终端中运行命令时获取 "SyntaxError: Unexpected identifier"

mysql - SQL查询以查找酒店的空闲房间

php - CodeIgniter 错误为 foreach() 提供的参数无效

database - 将单元格格式化为分钟 : seconds in google spreadsheets

java - Mongodb Java 查询日期范围

mongodb - 通过在 MongoDB 中使用批量插入与常规插入来提高性能

javascript - 从嵌套 JSON 中获取值

java - “can' t 从 BSON 类型字符串转换为 Date”MongoDB for Java 3.5