简体   繁体   中英

Python db Not equal Mongo Code not Working?

The following works when typed directly in the mongodb shell—I receive the correct output:

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

However, in Python 3, it's not working. Every time, only the if block runs. It does not matter if I use str or not in the query.

    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

...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:

$ne operator selects the documents where the value of the field is not equal (ie !=) to the specified value. This includes documents that do not contain the field.

db.serial_key.find({'key':{ '$ne':str(keys[i-1])}}) will return a mongo cursor. Thus your if condition will always be true resulting in document addition regardless of the presence of the same value.

If you want to verify that the key already exists you can query the value and check the mongo cursor count.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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