python mongodb检查文档是否存在(return True if document exists)

python mongodb检查文档是否存在(return True if document exists),第1张

概述python mongodb检查文档是否存在(return True if document exists)

作为一名mongodb初学者,经常需要在插入数据之前需要检查指定集合下,指定文档是否存在,翻了N久的文档。发现最新版的mongodb出了一个新方法:db.collection.countdocuments()

第一种方法:使用count_documents

count_documents ——不过该功能只在mongodb 4.0.3和python3.7之后才支持。

if not db.collection.count_documents({ 'username': chenxm.cc}, limit = 1):    # do something

limit=1  这个参数是查找至少存在一个匹配项,箱子匹配出现的次数是为了方便从集合中找到了数据,就停止继续扫描集合,而不是遍历整个集合。

如果是早起版本的mongdo和python版本

if db.collection.count({ 'username': 'chenxm.cc'}, limit = 1) != 0:  # do something

第二种方法:提取索引ID

db.collection.find({'username': 'chenxm.cc'}, {"_ID" : 1});

文档:

https://docs.mongodb.com/manual/reference/method/db.collection.countDocuments/

总结

以上是内存溢出为你收集整理的python mongodb检查文档是否存在(return True if document exists)全部内容,希望文章能够帮你解决python mongodb检查文档是否存在(return True if document exists)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/1154618.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存