Brett
Brett

Reputation: 12007

PyMongo returns an empty result set when a MongoDB client returns correct results

I have a simple MongoDB collection that I am accessing using PyMongo in my Python script.

I am filtering the query in Python using the dictionary:

{ "$and" : [
    { "bettinginterests" : { "$elemMatch" : { "runner.name" : "Jailhouse King" } } },
    { "bettinginterests" : { "$elemMatch" : { "runner.name" : "Tyrone Haji" } } }
    ]
}

And this returns correct results. However, I would like to expand the filter to be:

{ "$and" : [
    { "bettinginterests" : { "$elemMatch" : { "runner.name" : "Jailhouse King" } } },
    { "bettinginterests" : { "$elemMatch" : { "runner.name" : "Tyrone Haji" } } },
    { "summary.dist" : "1" }
    ]
}

And this is returning an empty result set. Now when I do this same query in my MongoDB client using:

db.race_results.find({ "$and" : [
    { "bettinginterests" : { "$elemMatch" : { "runner.name" : "Jailhouse King" } } },
    { "bettinginterests" : { "$elemMatch" : { "runner.name" : "Tyrone Haji" } } },
    { "summary.dist": "1" }
    ]
})

The results are returned correctly as expected.

I don't see any difference between the Python dictionary being passed as the query filter, and the js code being executed on my MongoDB client.

Does anyone see where there might be a difference? I'm at a loss here.

UPDATE:

Here is a sample record in my DB: https://gist.github.com/brspurri/8cefcd20a7f995145a81

UPDATE 2: Python Code to perform the query:

runner = "Jailhouse King"
opponent = "Tyrone Haji"
query_filter = {"$and": [
                    {"bettinginterests": {"$elemMatch": {"runner.name": runner}}},
                    {"bettinginterests": {"$elemMatch": {"runner.name": opponent}}},
                    { "summary.dist" : "1" }
                    ]
                }

try:
    collection = db.databases['race_results']
    entities = None
    if not query_filter:
        entities = collection.find().sort([("date", -1)])
    else:
        entities = collection.find(query_filter).sort([("date", -1)])

except BaseException, e:
    print('An error occured in query: %s\n' % e)

Upvotes: 2

Views: 2185

Answers (1)

Sede
Sede

Reputation: 61225

This line is probably the culprit.

collection = db.databases['race_results']

If db is your database you are doing it wrong. It should be

collection = db['race_results'] 

Upvotes: 1

Related Questions