Mercer
Mercer

Reputation: 9986

Return the count of a collection

How can I turn db.collection.count() into a Python script?

I just want it to return a number.

#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)

Thanks in advance.

Upvotes: 1

Views: 4104

Answers (2)

Mercer
Mercer

Reputation: 9986

#!/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()

Upvotes: 1

GHETTO.CHiLD
GHETTO.CHiLD

Reputation: 3416

you will need to connect to your database and then run the db.collection.count() to count the items in your collection in 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())

Upvotes: 2

Related Questions