计算 mongodb 中数组内的元素

Counting elements inside an array in mongodb

我想使用 python 和 pymongo 计算数组中元素的数量。这是数据。

{
"_id": 5,
"type": "Student",
"Applicates": [
    {
        "appId": 100,
        "School": "dfgdfgd",
        "Name": "tony",
        "URL": "www.url.com",
        "Time": "5/5/5-6/6/6",
        "Research": "dfgdfg",
        "Budge": 5000,
        "citizenship": "us",
        "Major": "csc",
        "preAwards": "None",
        "Advisor": "dfgdfg",
        "Evaluators": [
            {
                "abstractScore": 10,
                "goalsObjectivesScore": 20,
                "evalNum": 1
            },
            {
                "abstractScore": 30,
                "goalsObjectivesScore": 40,
                "evalNum": 2
            },
            {
                "abstractScore": 50,
                "goalsObjectivesScore": 60,
                "evalNum": 3
            }
        ]
    },
    {
        "appId": 101,
        "School": "dvdu",
        "Name": "jessy",
        "URL": "www.url.com",
        "Time": "4/4/4-6/6/6",
        "Research": "dfgdfg",
        "Budge": 7500,
        "citizenship": "us",
        "Major": "dfgdfg",
        "preAwards": "dfgfd",
        "Advisor": "dfgdfg",
        "Evaluators": [
            {
                "abstractScore": 70,
                "goalsObjectivesScore": 80,
                "evalNum": 1
            },
            {
                "abstractScore": 90,
                "goalsObjectivesScore": 100,
                "evalNum": 2
            }
        ]
    }
]}

所以我想获取 Evaluators 数组的大小。 {"appId" : 100} 会给出 3 而 {"appId" : 101} 会给出 2。我一直在玩 $size 但似乎无法得到它。

一种方法是遍历您的数组,然后在每次迭代中对该字典的求值器使用 len() 属性。

for obj in Applicates:
    count = len(obj['Evaluators'])

使用此语法 { $size: <expression> } 您可以计算数组中的项目数。看这里了解更多 > $size

查询return个文档。没有查询将 return 数组元素中 Evaluators 数组的大小 "appId" : 100`。但是以下笨拙的格式表达式将满足您的需求:

len(coll.find_one(
    { "Applicates.appId" : 100 }, 
    { "Applicates.$.Evaluators" : 1 }
)["Applicates"][0]["Evaluators"])

其中 coll 是集合对象。