【问题标题】:How can I remove N documents in PyMongo?如何在 PyMongo 中删除 N 个文档?
【发布时间】:2018-03-23 16:40:38
【问题描述】:

我正在尝试使用 PyMongo collection.remove({}) N 个文档。 在 mongodb 上,这类似于 this,PyMongo 等价物是什么?

谢谢

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    为了删除集合中的N个文档,你可以这样做

    1. bulk_writeDeleteOne 对集合的操作。 例如

      In [1]: from pymongo import MongoClient
              from pymongo.operations import DeleteOne
      
      
              client = MongoClient()
              db = client.test
              N = 2 
      
              result = db.test.bulk_write([DeleteOne({})] * N)
      
      In [2]: print(result.deleted_count)
      2
      
    2. delete_many 使用来自先前 find 的所有 id 的过滤器。 例如

      def delete_n(collection, n):
          ndoc = collection.find({}, ('_id',), limit=n)
          selector = {'_id': {'$in': [doc['_id'] for doc in ndoc]}}
          return collection.delete_many(selector)
      
      result = delete_n(db.test, 2)
      print(result.deleted_count)
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2019-08-31
      • 2018-11-21
      • 1970-01-01
      • 2021-09-15
      • 2012-04-07
      • 2021-06-23
      相关资源
      最近更新 更多