2014-11-02 44 views
1

的实例,我有MongoDB的IDSPyMongo:类型错误:spec必须快译通

id_list = [{u'_id': u'0'}, {u'_id': u'1'}, {u'_id': u'2'}, {u'_id': u'3'}, {u'_id': u'4'}] 

的列表,我想火一个单一查询的MongoDB,并得到匹配的文档回到相同的顺序名单。 但是,下面的代码导致TypeError: spec must be an instance of dict

from pymongo import MongoClient 

if __name__ == '__main__': 

    db = MongoClient() 

    sDB = db.test.users 
    id_list = [{u'_id': u'0'}, {u'_id': u'1'}, {u'_id': u'2'}, {u'_id': u'3'}, {u'_id': u'4'}] 
    print list(sDB.find(id_list[0:2])) 

回答

1

蒙戈查询语法必须使用,即:

collection.find({"_id": {"$in": [id1, id2, ..., idN]}}) 

要尊重它,第一只获得所需的ID,而不是一个类型的字典的名单列表:

needed_ids_only = map(lambda x: x['_id'], id_list[0:2]) 
# needed_ids_only is now == [u'0', u'1'] 

然后,其提供给 “$的” 运营商:

print list(sDB.find({"_id": {"$in": needed_ids_only}})) 

值得一提的是,如果你的文档中的_id是一个字符串,就像你提到的那样,一切正常。但是如果你的意思是一个ObjectId,那么在查询之前也需要将它转换为ObjectId。

所以,如果你的文件看起来是这样的:

> db.users.find().pretty() 
{ 
    _id: '0', 
    // ... 
}, 
{ 
    _id: '1', 
    // ... 
}, 
// ... 

那么一切都OK。但是,如果他们是这样的:

> db.users.find().pretty() 
{ 
    _id: ObjectId('0'), 
    // ... 
}, 
{ 
    _id: ObjectId('1'), 
    // ... 
}, 
// ... 

然后,它是需要_id值转换为的ObjectId:

from bson import ObjectId 
needed_ids_only = map(lambda x: ObjectId(x['_id']), id_list[0:2]) 
2

MongoDB使用字典的搜索和您提供的数组:

你举的例子:

id_list[0:2] is [{u'_id': u'0'}, {u'_id': u'1'}] 

,而不是你可以使用$in此:

db.test.users.find({'_id':{'$in': ["0", "1", "2"]}}) 
相关问题