以下在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 db not equal to query not working
......但它没有回答我的问题。
===================完整的主类代码======================== ==
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)
显示控制台输出的图像。
答案 0 :(得分:1)
来自mongodb docs:
$ne
运算符选择字段值不相等(即!=)的文档到指定值。这包括不包含该字段的文档。
db.serial_key.find({'key':{ '$ne':str(keys[i-1])}})
将返回一个mongo游标。因此,无论是否存在相同的值,您的if条件将始终为真,从而导致文档添加。
如果要验证密钥是否已存在,可以查询该值并检查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')