【问题标题】:DeprecationWarning: count is deprecated. Use Collection.count_documents instead弃用警告:不推荐使用计数。请改用 Collection.count_documents
【发布时间】:2021-08-09 21:48:11
【问题描述】:
def get_registered_user():
    users = collection_users.find({name:'john'}, {'regDate': regDate}).count()
    pprint.pprint("users:" + str(users))

在 mongoDB python 中使用 count() 方法时,我收到警告为“DeprecationWarning:count 已弃用。请改用 Collection.count_documents。”

Collection.count_documents() 只接受一个查询。如何同时通过以上两个查询?请帮忙。

【问题讨论】:

  • 您不能同时将两个查询传递给任何 mongodb 操作,因为这样做没有意义。您现有的代码可能已损坏。
  • @D.SM 有没有办法检查以上两个条件来计算最终结果
  • 在同一个字典中传递它们。

标签: python mongodb


【解决方案1】:

这里,find() 方法接受两个逗号分隔的条件。但count_documents() 不接受多个条件。

为此,可以使用$and 运算符。 $and 运算符使用逻辑 AND 连接两个或多个查询,并返回匹配所有条件的文档。

我们可以结合两个条件为

def get_registered_user():
    criteria = { '$and' : [ {name:'john'},{'regDate': regDate} ] }
    users = collection_users.count_documents(criteria)
    pprint.pprint("users:" + str(users))

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多