0

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.

enter image description here

2
  • There are several issues with your code. First, you are missing a reference to the serial_key collection in your insert statement: it should read db.serial_key.insert(...). Second, if I understand correctly what you're trying to do, the logic in your if statement is wrong—it will find one document whose key does not match keys[i-1], and then insert the new document anyway. Commented Oct 8, 2015 at 5:14
  • @JorgeAranda , I will add full main code. but sorry , this is official work , so , I haven't permission to add algo class. If you want I will put db screen shots Commented Oct 8, 2015 at 5:48

1 Answer 1

1

From mongodb docs:

$ne operator selects the documents where the value of the field is not equal (i.e. !=) 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')
Sign up to request clarification or add additional context in comments.

7 Comments

yes, I agree with you and thank you , but not solving my trouble. every time loop condition is TRUE.
I am sorry are you saying that even the new condition db.serial_key.find({'key':str(keys[i-1])}).limit(1).count() == 0 is always TRUE? If not what is the expected behavior?
@thegreenorge , I mean condition is always true. I want , when current key already in database, it is not again enter to database.
@uma the new condition will be true only if the key is not present in the database. Have you modified your original code with the changes I proposed?
@thegroureenoge of course sir. I put your code and check the result. thank you for your help. now , I think , it is better to other way.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.