MongoDB从聚合管道返回平面数组

时间:2019-12-18 19:28:57

标签: mongodb mongoose aggregation-framework

我希望聚合查询返回一个平面数组,而不是像.distinct()一样完全返回对象数组。

示例文档:

{
    type: 'pageview',
    url: 'https://example.com/something',
    visitorId: '5df7c38abbdb1506dc048451'
}

示例汇总:

db.accounts.events.aggregate( [
    // First stage
    { $match: { url: 'https://example.com/something' } },
    // Second stage
    { $group: { _id: "$visitorId", count: { $sum: 1 } } },
    // Third stage
    { $match: { count: { $gt: 10 } } }
] )

返回:

{ "_id" : ObjectId("5df7c38abbdb1506dc048451"), "count" : 13 }
{ "_id" : ObjectId("5df7c38abbdb1506dc048454"), "count" : 18 }
// ... and so forth

应返回:

[ ObjectId("5df7c38abbdb1506dc048451"), ObjectId("5df7c38abbdb1506dc048454") ]

我知道它在客户端很容易做到,但是我想知道mongodb是否也能够在聚合范围内做到这一点。

3 个答案:

答案 0 :(得分:1)

这将为您提供接近预期效果的结果:

db.collection.aggregate([
    // First stage
    { $match: { url: 'https://example.com/something' } },
    // Second stage
    { $group: { _id: "$visitorId", count: { $sum: 1 } } },
    // Third stage
    { $match: { count: { $gt: 10 } } },
    {
        $group: {
            _id: null,
            data: {
                $push: "$_id"
            }
        }
    },
    {
        $project: {
            _id: 0,
            data: {
                $reduce: {
                    input: "$data",
                    initialValue: [],
                    in: {
                        $concatArrays: ["$$value", ["$$this"]]
                    }
                }
            }
        }
    }
])

结果:

[
    {
        "data": [
            ObjectId("5df7c38abbdb1506dc048451"),
            ObjectId("5df7c38abbdb1506dc048454")
        ]
    }
]

答案 1 :(得分:1)

Definiton of db.collection.aggregate()说一个聚合:

  

返回:光标移动到最后阶段生成的文档   聚合管道操作,...

返回的游标包含文档,并且文档始终具有MongoDB document structure中定义的

因此,(仅)获取 values 数组的方法是使用已经发布的答案和以下讨论中描述的方法之一(即通过应用{{3} }(通过聚合返回的游标)。

答案 2 :(得分:0)

您可以在集合上使用[user@project]$ python3 --version Python 3.6.5 [user@project]$ which python3 /usr/bin/python3 [user@project]$ /usr/bin/python3 --version Python 3.6.8 [user@project]$ pyenv uninstall 3.6.5 pyenv: version `3.6.5' not installed 返回所需字段值的平面数组:

map

这是一种利用mongo的方法。问题是,它返回一个内部带有平面数组的对象。不幸的是,聚合总是会返回一个对象。您可以使用.cursor()。exec()链接聚合以获取db.accounts.events.aggregate( [ // First stage { $match: { url: 'https://example.com/something' } }, // Second stage { $group: { _id: "$visitorId", count: { $sum: 1 } } }, // Third stage { $match: { count: { $gt: 10 } } } ]).map(function(obj) { return obj._id }) 方法,但是我不确定这是否对您有帮助:

.toArray()