disruptive
disruptive

Reputation: 5946

MongoDB query doesn't behave as expected with nested elements

I'm trying to return results which match a value and also match on child properties. So I want to return say results which match the month and then match a range of values. However I find even the simple search, doesn't seem to return any results which I would expect.

Using pymongo my query is:

month = 2
results = db.master.find({"months": str(month)})

This should surely return all matching documents for the correct month. However I get no records returns for month=2

My data is stored in MDB as:

{
    "_id": {
        "$oid": "568d0bebc1bed847da7a2e6f"
    },
    "months": {
        "2": {
            "std_rank": 0.11338862902393358,
            "rank_gain": 0.6183933826187626,
            "gain": 0.9618213660245183,
            "std": 0.021891473641317716
        },
    "months": {
        "3": {
            "std_rank": 0.11338862902393358,
            "rank_gain": 0.6183933826187626,
            "gain": 0.9618213660245183,
            "std": 0.021891473641317716
        },   
    },
    "code": "VU"
}

One suggested answer works for filtering correct month, now the question is how to apply a filter to its child elements. For example:

results = db.master.find({}, {"_id": 0, "months." + str(month): 1, "months.std_rank": {"$lte": max_std_rank, "$gte": min_std_rank} } )

I get the following error:

pymongo.errors.OperationFailure: database error: Can't canonicalize query: BadValue >1 field in obj: { $gte: 0.0, $lte: 1.0 }

Upvotes: 3

Views: 905

Answers (1)

chridam
chridam

Reputation: 103445

Try the following query

results = db.master.find({ "months." + str(month) + ".std_rank": {"$lte": max_std_rank, "$gte": min_std_rank } }, { "_id": 0, "months." + str(month): 1 } )

which uses projection to return only the document matching the given month key.

Upvotes: 2

Related Questions