简体   繁体   English

Python db不等于Mongo代码不起作用?

[英]Python db Not equal Mongo Code not Working?

The following works when typed directly in the mongodb shell—I receive the correct output: 当直接在mongodb shell中键入以下代码时,我将收到正确的输出:

db.serial_key.find({key: {$ne : "5SNT0V"}})

However, in Python 3, it's not working. 但是,在Python 3中,它不起作用。 Every time, only the if block runs. 每次,只有if块运行。 It does not matter if I use str or not in the query. 我在查询中是否使用str都没有关系。

    for x in keys:
         i +=1;
         print('key %d  = ' %i ,  keys[i-1])  #out put: key 1  =  3ZOHSH

         # place values in dictionary
         keyrecord_record = {'key':keys[i-1],'b_p_code':x1}


         if(db.serial_key.find({'key':{ '$ne':str(keys[i-1])}})):
             db.insert(keyrecord_record)
         else:
             print('Record in DB')

Please, I expect some expert help. 请,我希望得到专家的帮助。 I'm trying to do this within one day. 我正试图在一天之内做到这一点。 I only want to write values that are not already in the database. 我只想编写数据库中尚未存在的值。

I found this question: Mongo db not equal to query not working 我发现了这个问题: Mongo数据库不等于查询不起作用

...but it does not answer my question. ...但是它不能回答我的问题。

===================full main class code========================== ==================完整的主类代码============================

from pymongo import MongoClient
from algo import algo


#take in put data
x1 = int(input("Enter a number(Brand_name+Pack_size) : "))
y1 = int(input("Enter a number: key Quntity "))

#create connection
client = MongoClient()

#create emty list
alist = []

#make database_table
db = client.product.serial_key
keyrecord_record = {}

#find table existing entry that code
f_cursor = db.find({"b_p_code": x1})

for document in f_cursor:
    alist.append(document['key'])
    #print(document['key']) //print expected result



if(x1 == ""  or y1==""):
    print("please enter valid no")
else:
    x = algo(x1,y1,alist)

    keys =x.id_generator()
    keys.sort(reverse=True)
    print('\n')
    i=0;
    for x in keys:
        i +=1;
        print('key %d  = ' %i ,  keys[i-1])

        # place values in dictionary
        keyrecord_record = {'key':keys[i-1],'b_p_code':x1}


        #not recived expected result. if key in database again print key
        if(db.serial_key.find({'key':{ '$ne':str(keys[i-1])}})):
            db.insert(keyrecord_record)
        else:
            print('Record in DB')


    print("\n")
    print("Batch No: come from db ")
    print('Generate Key beetween  %d00000 - %d00000'  % (x1 ,(x1+1)) )
    print("Startin Serial : " , keys[0])
    print("Ending  Serial : " , keys[len(keys)-1])



print('\n      Database Details   \n')
#print details
cursor = db.find()

for document in cursor:
    print(document['key'])
    #print(document)  

Image showing console out put. 该图显示了控制台输出。

在此处输入图片说明

From mongodb docs: 来自mongodb docs:

$ne operator selects the documents where the value of the field is not equal (ie !=) to the specified value. $ne运算符选择字段值不等于(即!=)指定值的文档。 This includes documents that do not contain the field. 这包括不包含该字段的文档。

db.serial_key.find({'key':{ '$ne':str(keys[i-1])}}) will return a mongo cursor. db.serial_key.find({'key':{ '$ne':str(keys[i-1])}})将返回一个mongo游标。 Thus your if condition will always be true resulting in document addition regardless of the presence of the same value. 因此,无论是否存在相同的值,您的if条件将始终为true,从而导致添加文​​档。

If you want to verify that the key already exists you can query the value and check the mongo cursor count. 如果要验证键是否已存在,可以查询该值并检查mongo游标计数。

The following code should do the trick. 以下代码可以解决问题。

for x in keys:
     i +=1;
     print('key %d  = ' %i ,  keys[i-1])  #out put: key 1  =  3ZOHSH

     # place values in dictionary
     keyrecord_record = {'key':keys[i-1],'b_p_code':x1}

     #check if already exists
     if(db.find({'key':str(keys[i-1])}).limit(1).count() == 0):
         db.insert(keyrecord_record)
     else:
         print('Record in DB')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM