[英]Python db Not equal Mongo Code not Working?
當直接在mongodb shell中鍵入以下代碼時,我將收到正確的輸出:
db.serial_key.find({key: {$ne : "5SNT0V"}})
但是,在Python 3中,它不起作用。 每次,只有if塊運行。 我在查詢中是否使用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')
請,我希望得到專家的幫助。 我正試圖在一天之內做到這一點。 我只想編寫數據庫中尚未存在的值。
我發現了這個問題: Mongo數據庫不等於查詢不起作用
...但是它不能回答我的問題。
==================完整的主類代碼============================
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)
該圖顯示了控制台輸出。
來自mongodb docs:
$ne
運算符選擇字段值不等於(即!=)指定值的文檔。 這包括不包含該字段的文檔。
db.serial_key.find({'key':{ '$ne':str(keys[i-1])}})
將返回一個mongo游標。 因此,無論是否存在相同的值,您的if條件將始終為true,從而導致添加文檔。
如果要驗證鍵是否已存在,可以查詢該值並檢查mongo游標計數。
以下代碼可以解決問題。
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.