查询MongoDB中的空值 [英] Querying null value in MongoDB
问题描述
使用 pymongo ,我试图检索集合中SmallUrl
与null
不同的文档.我正在尝试获取names
键和SmallUrl
键.
Using pymongo I am trying to retrieve the documents in a collection that have a SmallUrl
different from null
. I'm trying to get the names
key and the SmallUrl
key.
如果仅寻找Name
,则查询运行正常.但是,由于我想从结果中过滤出SmallUrl
值为null
的文档,因此当我在查询中包含this时,查询什么都不会返回.
If I look for the Name
only, the query runs fine. However, since I want to filter out from the results the documents that have a null
value for SmallUrl
, when I include the this in the query, the query returns nothing.
这是MongoDB的结构:
This is the MongoDB structure:
{u'Images': {u'LargeUrl': u'http://somelink.com/images/7960/53.jpg',
u'SmallUrl': u'http://somelink.com/images/7960/41.jpg'}
u'Name': u'Some Name',
u'_id': ObjectId('512b90f157dd5920ee87049e')}
{u'Images': {u'LargeUrl': u'http://somelink.com/images/8001/53.jpg',
u'SmallUrl': null}
u'Name': u'Some Name Variation',
u'_id': ObjectId('512b90f157dd5820ee87781e')}
这是查询功能:
def search_title(search_title):
$ne
''' Returns a tuple with cursor (results) and the size of the cursor'''
query = {'Name': {'$regex': search_title, '$options': 'i'}, 'SmallUrl': {'$exists': True}}
projection = {'Name': 1, 'Images': 1}
try:
results = movies.find(query, projection)
except:
print "Unexpected error: ", sys.exc_info()[0]
$ne
return results, results.count()
我是MongoDB的新手,我已经尝试了不同的查询.我用过$and
,$not
,{'$ne': 'null'}
}.我还在mongoShell中运行了查询,但结果相同.这是我在shell中查询的一个示例:
I am new to MongoDB I tried different queries already. I have used $and
, $not
, {'$ne': 'null'}
}. I also ran the queries in the mongoShell, but same result. This is an example of what I have queried in the shell:
db.myCollection.find({'Name': {'$regex': 'luis', '$options': 'i'}, 'SmallUrl': {'$ne': null}})
我想知道我在做错什么.
I would like to know what I am doing wrong.
推荐答案
您的查询不起作用,因为您应使用"Images.SmallUrl"而不是"SmallUrl"作为查询键. 我的测试集:
your query does not work because you should use 'Images.SmallUrl' instead of 'SmallUrl' for the key of query. my test collection:
> db.t.find()
{ "_id" : ObjectId("512cdbb365fa12a0db9d8c35"), "Images" : { "LargeUrl" : "http://aaa.com", "SmallUrl" : "http://bb.com" }, "Name" : "yy" }
{ "_id" : ObjectId("512cdc1765fa12a0db9d8c36"), "Images" : { "LargeUrl" : "http://aaa.com", "SmallUrl" : null }, "Name" : "yy" }
和我的测试查询:
> db.t.find({'Images.SmallUrl': {$ne: null}})
{ "_id" : ObjectId("512cdbb365fa12a0db9d8c35"), "Images" : { "LargeUrl" : "http://aaa.com", "SmallUrl" : "http://bb.com" }, "Name" : "yy" }
希望能提供帮助^ _ ^
Hope to help ^_^
这篇关于查询MongoDB中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!