我有一个文档集示例:

{name:"Danny", age:20, gender: 0}
{name:"Jordan", age:15, gender: 1}
{name:"Li Mei", age:20, gender: 1}
{name:"Soojin", age:17, gender: 0}
{name:"Zhang Ming", age:22, gender: 1}

我想通过按性别分组得到以下结果

{
  "Test field":[{name:"Danny", age: 20}, {name:"Soojin", age: 17}]
}
{
  "Test field":[{name:"Jordan", age: 15}, {name:"Li Mei", age: 20}, {name: "Zhang Ming", age: 22}]
}

什么查询可以实现这一点?

推荐答案

试试这个:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$gender",
      "Test Field": {
        "$push": {
          age: "$age",
          name: "$name"
        }
      }
    }
  },
  {
    "$project": {
      _id: 0
    }
  }
])

看到它工作here.

Mongodb相关问答推荐

MongoDB索引使用

如何在MongoDB中对两个数组进行分组?

无法配置数据源:未指定url属性,无法为 MongoDb 配置嵌入数据源

Mongo按最大分组排序

DB 中的引用对象在 GraphQL 查询中返回 null

有没有办法在 Prisma for MongoDB 的模式中显式声明 int32?

Nestjs中不同语言数据的mongodb聚合代码

使用 mongodb 时是否需要规范化数据库?

Mongodb 仅在值唯一时插入,否则更新 - 在 node.js 中

mongoose通过引用属性查找文档

Mongo查找对象内最长数组的查询

mongodb 模式设计命名约定

Mongoose 和新架构:返回ReferenceError: Schema is not defined

字段类型在 MongoDB 索引中是否重要?

try 解析序列化 JSON 字符串时处理 MongoDB 的 ISODate()

mongo - 如何查询嵌套的 json

Mongoose 不创建新集合

MongoDB聚合将字符串数组连接到单个字符串

python + pymongo:如何从 for 循环中在 mongo 中的现有文档上插入新字段

有没有办法执行更新操作的dry run?