如何将db.collection.count()
变成Python脚本?
我只想让它返回一个数字。
#import json file to MongoDB
logger.info(' Import du fichier .json vers la base MongoDB')
#subprocess.call('mongoimport --db AutoPrivilege -c cars stockvo.json --jsonArray --upsert --drop',shell=True)
p = subprocess.Popen(['mongoimport', '--db', 'myBD', '-c', 'cars', '/opt/data/stockvo.json', '--jsonArray', '--upsert', '--drop'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if stdout:
logger.info(stdout)
if stderr:
logger.error(stderr)
提前致谢。
答案 0 :(得分:2)
您将需要连接到您的数据库,然后运行db.collection.count()
来计算您的集合中的项目在python中。
import pymongo
# connect to mongodb instance
conn = pymongo.MongoClient('localhost')
# connect to the database
db = conn['mydb']
# print a count of the items in our collection
print(db.collection.count())
答案 1 :(得分:1)
#!/usr/bin/env python
from pymongo import MongoClient
#connect to mongodb instance
connection = MongoClient("localhost")
# connect to the myDB database and the stock collection
db = connection.myDB.stock
# print out the count
print(db.count())
# close the connection to MongoDB
connection.close()