目前没有方法能够直接拿到整列的数据,因此使用for
循环获取数据,比如获取全部的_id
:
[i['_id'] for i in coll.find({}, {"_id": 1})]
示例代码
from pymongo import MongoClient
import numpy as np
# 指定数据库
mongo_conn = MongoClient(host='localhost', port=27017)
mongo_db = mongo_conn.get_database("test") # 指定数据库
coll = mongo_db.get_collection("people")
# 添加数据
[coll.insert_one({"num": i, "letter": np.random.choice(a=['a', 'b', 'c', 'd'])}) for i in range(5)]
# 获取一列数据:_id
all_num = [i['num'] for i in coll.find({}, {"num": 1})] # 获得一列数据
print(all_num)