Reputation: 515
Given mongo document like below, how to efficiently find all documents and return student_id field as integer?
{
"_id" : ObjectId("58dd757910d81946b8ff853a"),
"student_id": "4169506398",
"first_name": "steven",
"last_name": "smith",
"date_of_birth": "02-07-1988"
}
{
"_id" : ObjectId("58dd757910d81946b8ff853b"),
"student_id": "6902",
"first_name": "michael",
"last_name": "clarke",
"date_of_birth": "05-30-1988"
}
Expected result (in Json):
{
"student_id": 4169506398
}
{
"student_id": 6902
}
I've 29000 records. Getting documents using db.find({}) and casting student_id to integer when looping might have performance issue.
Upvotes: 0
Views: 1426
Reputation: 61225
You can't do this without client side processing or map reduce.
mylist = map(int, db.collection.distinct('student_id'))
which yields a list of student_id
of type int
in PY2 or iterator object in PY3
You can also use the .aggregate()
method as shown here if "student_id" is not unique within the collection and you don't want to de-duplicate the result.
Upvotes: 1