I want to count the number of elements in an array using python and pymongo. Here is the data.
{
"_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
}
]
}
]}
So I want to get the size of the Evaluators array. {"appId" : 100} would give 3 and {"appId" : 101} would give 2. I have been playing around with $size but cant seem to get it.
Queries return documents. No query will return the size of the Evaluators
array in the array element with "appId" : 100`. But the following awkwardly formatted expression will so what you want:
len(coll.find_one(
{ "Applicates.appId" : 100 },
{ "Applicates.$.Evaluators" : 1 }
)["Applicates"][0]["Evaluators"])
where coll
is the Collection object.
One approach would be to loop through your array, and then on each iteration use len() on that dict's Evaluators property.
for obj in Applicates:
count = len(obj['Evaluators'])
With this syntax { $size: <expression> }
you can count number of items in an array. See here for more > $size
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.