[英]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.