【问题标题】:MongoDB return True if document exists如果文档存在,MongoDB 返回 True
【发布时间】:2014-09-29 13:57:44
【问题描述】:

如果用户 ID 已经存在,我想从我的集合中返回 true,否则返回 false。我有这个函数,但它总是返回 True

def alreadyExists(newID):
    if db.mycollection.find({'UserIDS': { "$in": newID}}):
        return True
    else:
        return False

如果用户 id 已经存在,我怎样才能让这个函数只返回 true?

【问题讨论】:

    标签: python mongodb pymongo tornado-motor


    【解决方案1】:

    注意:此答案已过时。最新版本的 MongoDB 可以使用更有效的方法db.collection.countDocuments。请参阅 Xavier Guihot 的 the answer 以获得更好的解决方案。

    find 不返回布尔值,它返回 cursor。要检查该游标是否包含任何文档,请使用游标计数方法。

    if db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0.

    顺便问一下:newID 是一个数组吗?如果不是,则不应使用$in-运算符。你可以简单地做find({'UserIDS': newID})

    【讨论】:

    • 我只会在这个答案中添加一个仅包含 '_id':1 设置的投影,因为数据库不会返回整个对象,每毫秒和字节计数 :)
    • 使用 .limit(1) 将结果集限制为 1 可能是对数据库的另一个有价值的提示
    • @Konstantin 所以用 find_one() 代替?
    • 哦,find_one() 不进行投影。 find() 是的!
    • 这是低效的。对于性能,我建议使用 Xavier 的回答中所述的“count_documents”。
    【解决方案2】:

    Mongo 4.0.3/PyMongo 3.7.0开头,我们可以使用count_documents

    if db.collection.count_documents({ 'UserIDS': newID }, limit = 1) != 0:
      # do something
    

    与可选参数limit 一起使用,这提供了一种查找是否存在至少一个匹配项的方法。

    限制匹配出现的次数会使集合扫描在找到匹配项后立即停止,而不是遍历整个集合。


    请注意,这也可以写成如下,因为1 在python 条件下被解释为True

    if db.collection.count_documents({ 'UserIDS': newID }, limit = 1):
      # do something
    

    在早期版本的Mongo/Pymongo 中,可以使用count(在Mongo 4 中已弃用并替换为count_documents):

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

    【讨论】:

      【解决方案3】:

      如果您使用的是 Motor,find() 不会与数据库进行任何通信,它只是创建并返回一个 MotorCursor:

      http://motor.readthedocs.org/en/stable/api/motor_collection.html#motor.MotorCollection.find

      由于 MotorCursor 不是 None,Python 将其视为“真”值,因此您的函数返回 True。如果您想知道是否存在至少一个与您的查询匹配的文档,请尝试 find_one():

      @gen.coroutine
      def alreadyExists(newID):
          doc = yield db.mycollection.find_one({'UserIDS': { "$in": newID}})
          return bool(doc)
      

      请注意,使用 Tornado 执行 I/O 需要“协程”和“屈服”。你也可以使用回调:

      def alreadyExists(newID, callback):
          db.mycollection.find_one({'UserIDS': { "$in": newID}}, callback=callback)
      

      有关回调和协程的更多信息,请参阅电机教程:

      http://motor.readthedocs.org/en/stable/tutorial.html

      如果您使用的是 PyMongo 而不是 Motor,则更简单:

      def alreadyExists(newID):
          return bool(db.mycollection.find_one({'UserIDS': { "$in": newID}}))
      

      最后一点,MongoDB 的 $in 运算符采用值列表。 newID 是一个列表吗?也许你只是想要:

      find_one({'UserIDS': newID})
      

      【讨论】:

      • 如何在 Mongo Shell 中编写这个?使 Mongo Shell 返回布尔值。
      【解决方案4】:

      mongodb查询中的一种线性解决方案

      db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0 ? true : false
      

      【讨论】:

        【解决方案5】:
        return db.mycollection.find({'UserIDS': newID}).count > 0
        

        【讨论】:

          【解决方案6】:

          这对我有用

          result = num.find({"num": num}, { "_id": 0 }) 
          if result.count() > 0:  
             return
          else:
             num.insert({"num": num, "DateTime": DateTime })
          

          【讨论】:

            【解决方案7】:
            def alreadyExists(newID):
                retuen db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-11-07
              • 2022-01-05
              • 2011-05-05
              • 2011-02-18
              • 1970-01-01
              相关资源
              最近更新 更多