【问题标题】:How to run raw mongodb commands from pymongo如何从 pymongo 运行原始 mongodb 命令
【发布时间】:2015-02-02 13:13:36
【问题描述】:

mongo 命令行中我可以运行

db.my_collection.stats()

我需要从 Python 获取我的收藏统计信息,所以我尝试了

from pymongo import MongoClient

client = MongoClient()
db = client.test_database

collection = db.test_collection

collection.stats()

但我明白了

TypeError: 'Collection' object is not callable. 
If you meant to call the 'stats' method on a 'Collection' object it is failing because no such method exists.

这是因为pymongo 不支持这种方法。如何通过Python 将原始mongoDB 命令发送到mongo

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:
    from pymongo import MongoClient
    
    client = MongoClient()
    
    db = client.test_database
    
    print(db.command("collstats", "test_collection"))
    

    【讨论】:

      【解决方案2】:

      使用PyMongo的方法1:

      client = pymongo.MongoClient(host = "127.0.0.1", port = 27017)
      db = client.test_database
      db.command("dbstats") # prints database stats for "test_db"
      db.command("collstats", "test_collection") # prints collection-level stats
      

      这可以在 Django 中使用这种方法来完成。

          from django.db import connections
      
          database_wrapper = connections['my_db_alias']
          eggs_collection = database_wrapper.get_collection('eggs')
          eggs_collection.find_and_modify(...)
      

      来自django-mongodb-engine docs

      django.db.connections 是一个类字典对象,它包含所有 数据库连接——也就是说,对于 MongoDB 数据库, django_mongodb_engine.base.DatabaseWrapper 实例。

      这些实例可用于获取 PyMongo 级别的连接, 数据库和集合对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-07
        • 2018-05-16
        • 1970-01-01
        • 1970-01-01
        • 2018-03-13
        相关资源
        最近更新 更多