【问题标题】:Querying null value in MongoDB在 MongoDB 中查询空值
【发布时间】:2013-02-11 09:15:57
【问题描述】:

使用 pymongo 我正在尝试检索集合中具有与 null 不同的 SmallUrl 的文档。我正在尝试获取names 密钥和SmallUrl 密钥。

如果我只查找Name,则查询运行良好。但是,由于我想从结果中过滤掉具有 null 值的文档,当我在查询中包含 this 时,查询不会返回任何内容。

这是 MongoDB 结构:

{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 中查询的一个示例:

db.myCollection.find({'Name': {'$regex': 'luis', '$options': 'i'}, 'SmallUrl': {'$ne': null}})

我想知道我做错了什么。

【问题讨论】:

  • 在 python 中使用 None 代替 null

标签: mongodb pymongo


【解决方案1】:

您的查询不起作用,因为您应该使用“Images.SmallUrl”而不是“SmallUrl”作为查询键。 我的测试集:

> 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" }

希望能帮到你^_^

【讨论】:

  • Python中没有null这样的东西
【解决方案2】:

null 的 pymongo 版本是 Python None。所以query 应该是这样的:

query = {
    'Name': {'$regex': search_title, '$options': 'i'}, 
    'Images.SmallUrl': {'$ne': None}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2015-06-07
    相关资源
    最近更新 更多