我在集合中有属性(home
)数据。每个家庭可以拥有多个所有者,并存储为单独的字段,例如{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 }
])
一个例子: DATA
{_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}
}
答案 0 :(得分:1)
据我所知,聚合框架尚不可能将多个字段重新整形为数组值(一个元素包含一个包含一个元素的元素是可能的,但没有用)。以下新功能解决了这个缺点,请投票支持 - “$ array aggregation expression” - https://jira.mongodb.org/browse/SERVER-8141