如何在pymongo中编写mongodb查询

时间:2015-04-28 19:11:15

标签: python mongodb pymongo

以下查询适用于mongodb shell:

db.user.count( {$and: [ {"agent_id":{$exists:true}}, {"is_agent":{$ne:true}} ] } )

当我在python中尝试时,我会得到一个不同的答案。这是python代码:

import pymongo
from pymongo import MongoClient

def getCollection(cient,dbname,collection):
    """Return a colleciton based on client, db and collection"""
    data_base = getattr(client, dbname)
    collObject = getattr(data_base, collection)
    return collObject   

userColl = getCollection(client, "hkpr_restore","user")

usersWithAgents = userColl.count( {"$and": [ {"agent_id":{"$exists":"true"}}, {"is_agent":{"$ne":"true"}} ] } )

print usersWithAgents

对于mongo shell查询,结果大约为11,000,对于python脚本查询,结果大约为17,000。

1 个答案:

答案 0 :(得分:0)

您应该使用:

"$exists": True

而不是

"$exists": "true"

$ne也一样。