hashark
hashark

Reputation: 351

MongoDB - finding entries using a nested dictionary

I have a MongoDB that I use with python. My entries that looks as follows:

{
   a: something
   b: something
   c: {
        d: something
        e: something
        f: something
       }
}

I want to query for entries that have a specific values for d and e but I don't care about the value in f.

I tried not specifying f at all (similarly to when I don't care about the b value where I just not adding it to the query):

{
   a: a_value
   b: b_value
   c: {
        d: d_value
        e: e_value
       }
}

I also tried to use:

{
   a: something
   b: something
   c: {
        d: something
        e: something
        f: { $exists : 1 }
       }
}

but none of these worked (in fact, I got no results at all)

How my query shall look like?

thanks!

Upvotes: 6

Views: 5672

Answers (2)

Att Righ
Att Righ

Reputation: 1779

Extending hashark's answer above. Here is some code to build the query from an object in python.

def obj_to_query(obj, prefix=""):
    "Convert a mongo object into a query."
    query = {}
    for k, v in obj.items():
        if not isinstance(v, dict):
            query[prefix + k] = v
        else:
            query.update(obj_to_query(v, prefix=prefix + k + "."))

    return query

Upvotes: 1

hashark
hashark

Reputation: 351

I found the solution. The query shall look as follows:

{
   a: something
   b: something
   c.d: something
   c.e: something
}

I hope it helps someone :-)

Upvotes: 15

Related Questions