python 连接 mongodb 获取部分字段数据并换行写入txt文件

#coding=utf-8
import sys
import datetime
sys.path.append("./")
from pymongo import MongoClient

#建立MongoDB数据库连接
client = MongoClient('数据库的IP地址', 端口号) # MongoClient('localhost', 27017)

db_data = client.test
db_data.authenticate("账号", "密码")

#用户验证
tableName = "AccountCheck" #数据表
# collection=db_data.tableName

#连接所用集合,也就是我们通常所说的表
all_num = getattr(db_data, tableName).find().limit(20)
print("all_num",all_num)
phone_list=[]
for data in all_num:
#     Mobile=data.get("userMobile")
#     print(type(Mobile),Mobile)
#     phone_list.append(data.get("userMobile"))
# print(','.join(phone_list))
# print(len(phone_list))
    with open('文件名.txt', 'a') as f:
        f.write(data.get("userMobile"))
        f.write("\n")


posted @ 2020-10-11 00:35  莫贞俊晗  阅读(426)  评论(0编辑  收藏  举报