计算mongodb中数组内的元素

时间:2015-02-13 00:54:00

标签: python mongodb pymongo

我想使用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但似乎无法得到它。

3 个答案:

答案 0 :(得分:1)

查询返回文档。没有查询将使用" appId"返回数组元素中Evaluators数组的大小。 :100`。但是下面那个格式化的表达式将会是你想要的:

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

其中coll是Collection对象。

答案 1 :(得分:0)

一种方法是循环遍历数组,然后在每次迭代时在该dict的Evaluators属性上使用len()。

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

答案 2 :(得分:0)

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