【问题标题】:Create results of a specific shape from MongoDB query/aggregation pipeline从 MongoDB 查询/聚合管道创建特定形状的结果
【发布时间】:2021-03-17 16:30:40
【问题描述】:

考虑这个模型:

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 术语对此使用了什么,所以也许这就是我找不到正确答案的原因。

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

【问题讨论】:

    标签: mongodb mongoose aggregation


    【解决方案1】:
    • $matchgoals大于0
    • $group所有文件并准备firstnamelastname数组
    • $project 制作一个 result 数组,$filter 在 concat firstnamelastname 之后使用 $concatArrays 迭代数组循环,这将删除空字符串 来自数组和 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", ""] }
            }
          }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多