如何聚合、筛选嵌套数组并投影选定的嵌套字段?

我有以下数据:

{
  "teacher": "Ben",
  "students": [
    {
      "name": "Liz",
      "age": 8,
      "pets": 1
    },
    {
      "name": "Jon",
      "age": 9,
      "pets": 3
    },
    {
      "name": "Eva",
      "age": 9,
      "pets": 2
    }
  ]
}

..并想要查询以获得此结果:

{
  "teacher": "Ben",
  "students": [
    {
      "name": "Jon",
      "pets": 3
    },
    {
      "name": "Eva",
      "pets": 2
    }
  ]
}

我可以按某个年龄进行过滤,但如何才能只返回嵌套的学生数据中的namepets个字段呢?我试图以所有我能想到的方式投射这些油田,但运气不佳,所以我猜我可能找错了地方.

db.classes.aggregate([
  { "$match": {} },
  { "$project": {
    "_id": 0,
    "teacher": 1,
    "students": {
      "$filter": {
        input: "$students",
        cond: {
          "$eq": [ "$$this.age", 9 ],
        }
      }
    }
  }}
])

推荐答案

你可以加一个$project级的stage

 //previous stages 
 {
    $project: {
      "students.age": 0
    }
  }

或者,您可以使用$unset阶段删除不需要的字段

db.collection.aggregate([
  { $match: {} },
  {
    $project: {
      _id: 0,
      teacher: 1,
      students: {
        $filter: {
          input: "$students",
          cond: { $eq: [ "$$this.age", 9 ] }
        }
      }
    }
  },
  { $unset: "students.age" }
])

playground

我觉得如果先考$addFields分,再考$unset分,那就更干净了

db.collection.aggregate([
  { $match: {} },
  {
    $addFields: {
      students: {  //fields you just want to add, here overwrites students
        $filter: {
          input: "$students",
          cond: { $eq: [ "$$this.age", 9 ] }
        }
      }
    }
  },
  { $unset: [ "students.age", "_id" ] } //remove just the ones not needed
])

playground

Mongodb相关问答推荐

MongoDB 对特定搜索查询的响应时间较长

MongoDB 根据最新日期查询多个不同的值

优化游戏应用程序的反馈表单后端设计

如何对 MongoDB setWindowFields 中当前文档以外的文档进行操作

将 MongoDB 转移到另一台服务器?

声明多个模式后无法从数据库中获取数据(mongoose + express + mongodb

在mongoose中添加多个验证

我怎样才能更快地scrape

使用管道聚合的 Spring Data MongoDB 查找

什么是 mongodb 中的admin数据库?

在 Mongoose 中填写所有必填字段

如何在 mongoDB 中聚合巨大的数组?

C# mongodb driver 2.0 - 如何在批量操作中更新插入?

Mongoose 连接认证失败

如何使用 MongoDB 和 Mongoid 在 Rails 3 上进行适当的数据库测试 (TDD)

我如何使用 Twitter 的流 api 中的推文并将它们存储在 mongodb 中

在 Ubuntu 13.10 (saucy) 中安装 Mongodb PHP 扩展的最简单方法?

MongoDB 和 Robomongo: Can't connect (authentication)

MongoDb 聚合 $match 错误:Arguments must be aggregate pipeline operators

MongoDb 连接被拒绝