如何在不使用 $group 的情况下使用 $push 从对象列表中仅获取特定字段的列表

How to get only List of specific field from List of objects using $push without using $group

我在 mongoDB

中有一个对象列表

[{ "name":"Joy", "age":23 }, { "name":"Nick", "age":26 }, { "name":"Merry", "age":27 }, { "name":"Ben", "age":20 }]

我需要一个包含年龄列表的结果,例如

ages:[23,26,27,20]

实际上这些对象只是为了举例。我正在使用一些不同的对象,我可以在 $push 之后使用 $group 来获得结果但是我们可以在没有 $group 的情况下获得这个结果吗?

如果 "objects" 是指 MongoDB 文档,那么您可以使用按 null 分组的技巧,这基本上会将所有文档合并为一个结果:

db.collection.aggregate([
    {
        $group: {
            _id: null,
            ages: { $push: "$age" }
        } 
    }
])

您将得到以下结果:

{ "_id" : null, "ages" : [ 23, 26, 27, 20 ] }