在MongoDB中的$ lookup上使用$ slice和$ map?

时间:2018-06-27 23:26:18

标签: mongodb aggregation-framework

- 嗨,我有一个带有查询的聚合查询,我需要从该查询中投影特定字段并将它们切片。这是我到目前为止所做的。

{
$lookup: {
  from: 'users',
  localField: 'users',
  foreignField: '_id',
  as: 'users',
}},

我添加了取消声明

{
$unwind: {
  path: '$users',
  preserveNullAndEmptyArrays: true
}},

我添加了组声明

{ $group: { _id: { _id: '$_id', createdAt: '$createdAt', updatedAt: '$updatedAt' }, users: { $addToSet: '$users', } } },

要在用户数组中投影特定字段,我做了:

{
$project: {
  _id: '$_id._id',
  createdAt: '$_id.createdAt',
  updatedAt: '$_id.updatedAt',
  // users: {
  //   $slice: [
  //     "$users",
  //     skip,
  //     limit
  //   ]
  // },
  users: {
    $map: {
        input: '$users',
        as: 'user',
        in: {
          email: '$$user.email',
          name: '$$user.name',
          username: '$$user.username',
          updatedAt: '$$user.updatedAt'
        }
     }
  }
}},

我的问题是,如何在此范围内使用$ slice?

1 个答案:

答案 0 :(得分:-1)

我不知道这是什么“合法” ,但是,我已经在 $ group 中的 $ addToSet 语句中添加了字段,所以现在我可以在映射的字段中使用 $ slice

{
    $group: {
      _id: {
        _id: '$_id',
        createdAt: '$createdAt',
        updatedAt: '$updatedAt',
      },
      users: {
        $addToSet: {
          _id: '$users._id',
          email: '$users.email',
          name: '$users.name',
          username: '$users.username',
          updatedAt: '$users.updatedAt'
        }
      }
    }
  }

现在,我可以轻松地在 $ project 语句中执行 $ slice

{
    $project: {
      _id: '$_id._id',
      users: {
        $slice: [
          "$users",
          skip,
          limit
        ]
      }
    },
  }

如果有人有更好的解决方案,我想知道。