从MongoDB查询/聚合管道创建特定形状的结果

从MongoDB查询/聚合管道创建特定形状的结果,mongodb,mongoose,aggregation,Mongodb,Mongoose,Aggregation,以这种模式为例: const user = { firstname: { type: String, default: '' }, lastname: { type: String, default: '' }, goals: { type: Number, default: 0 }, }; 本系列: [{ id: 1, firstname: 'paul', lastname: 'pogba', goals: 2, }, { id: 2, firstname

以这种模式为例:

const user = {
  firstname: { type: String, default: '' },
  lastname: { type: String, default: '' },
  goals: { type: Number, default: 0 },
};
本系列:

[{
  id: 1,
  firstname: 'paul',
  lastname: 'pogba',
  goals: 2,
},
{
  id: 2,
  firstname: 'fred',
  lastname: '',
  goals: 2,
},
{
  id: 3,
  firstname: '',
  lastname: 'rashford',
  goals: 5,
},
{
  id: 4,
  firstname: 'luke',
  lastname: 'shaw',
  goals: 0,
}]
我想执行一个查询(我想它需要是一个聚合管道),返回一个数组,其中每个匹配文档中的每个可用名称都是数组中的一个条目。因此,使用上面的示例,假设我希望获得具有1个或多个目标的用户。查询/聚合管道的最终输出为:

['paul', 'pogba', 'fred', 'rashford']
注意

  • 不包括空字符串
  • 如果两个名称在给定文档中都可用,则将包括这两个名称
  • luke shaw
    的名字被排除在外,因为luke shaw不匹配(目标少于1个)
我甚至不知道MongoDB的术语是什么,所以也许这就是为什么我找不到正确答案的原因

我怎样才能做到这一点?谢谢

  • $match
    目标
    大于0
  • $group
    所有文档并准备
    firstname
    lastname
    数组
  • $project
    使用
    $concatarray
    生成数组的一个
    结果,
    $filter
    在concat
    firstname
    lastname
    之后迭代数组循环,这将删除空字符串 从单个结果中的数组和concat

db.collection.aggregate([
  { $match: { goals: { $gt: 0 } } },
  {
    $group: {
      _id: null,
      firstname: { $push: "$firstname" },
      lastname: { $push: "$lastname" }
    }
  },
  {
    $project: {
      _id: 0,
      result: {
        $filter: {
          input: { $concatArrays: ["$firstname", "$lastname"] },
          cond: { $ne: ["$$this", ""] }
        }
      }
    }
  }
])