我home
在集合中有 property() 数据。每个家庭可以有多个所有者并存储为单独的字段,例如{home: 1, owner1: Fred, owner2: Jason, owner3: Stan}
我想获取前 X 所有者名称的列表。作为 mongodb 的新手,我能够改编一个基本示例来聚合和计算一个字段(owner1
),但我不知道如何组合来自 owner1、owner2、owner3 的名称然后计数。
我现在使用 pymongo
x = data2009.aggregate([
{ "$group": { "_id": "$OWNER1", "value": { "$sum": 1 } } },
{ "$sort": { "value": -1 } },
{ "$limit": 50 }
])
一个例子:数据
{_id:1, home: 1, OWNER1: "Fred", OWNER2: "Stan", OWNER2: ""}
{_id:2, home: 2, OWNER1: "Jason", OWNER2: "Fred", OWNER2: "Stan"}
{_id:3, home: 3, OWNER1: "Fred", OWNER2: "Tim", OWNER2: "Stan"}
{_id:4, home: 4, OWNER1: "Stan", OWNER2: "", OWNER2: ""}
输出将是
{
{_id: Stan, value: 4}
{_id: Fred, value: 3}
{_id: Jason, value: 1}
{_id: Tim, value: 1}
}