简体   繁体   中英

Mongodb aggregation, how to combine or merge fields then count

I have property( home ) data in a collection. Each home can have multiple owners and is stored as separate fields for example {home: 1, owner1: Fred, owner2: Jason, owner3: Stan} I want to get the list of top X owner names. Being new to mongodb I was able to adapt a basic example to aggregate and count one field ( owner1 ) but I don't see how to combine the names from owner1, owner2, owner3 and then count.

What I have now using pymongo

x = data2009.aggregate([
    { "$group": { "_id": "$OWNER1", "value": { "$sum": 1 } } },
    { "$sort": { "value": -1 } },
    { "$limit": 50 }
])

An example: 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: ""}

Output would be

{
{_id: Stan, value: 4}
{_id: Fred, value: 3}
{_id: Jason, value: 1}
{_id: Tim, value: 1}
}

As far as I know, reshaping multiple fields into an array value is not yet possible with the aggregation framework (one element into an array containing the one element is possible, but not useful). The following New Feature addresses this shortcoming, please vote for it - "$array aggregation expression" - https://jira.mongodb.org/browse/SERVER-8141

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM