简体   繁体   中英

Python PyMongo Count Occurrences of Array Item

The values I need to count are an array of values so rather than $myField being the key to an item, it's the array elements I need to count so the number of corn, wheat, barley in all the documents.

"myField": [
  "corn",
  "wheat"
],

This is the code for a single item:

for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

Now it's time for $unwind , which transforms an array of values into a series of documents, each with a single value where the array had been:

c = MongoClient().test.collection
c.delete_many({})
c.insert_many([
    {"myField": ["corn", "wheat"]},
    {"myField": ["corn", "barley"]},
    {"myField": ["hops"]},
])

for result in c.aggregate([{
    "$unwind": "$myField"
}, {
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

The output:

barley: 1
wheat: 1
hops: 1
corn: 2

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