如何在 pymongo 中编写 mongodb 查询

how to write a mongodb query in 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。

你应该使用:

"$exists": True

而不是

"$exists": "true"

$ne也一样。