Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 498
hashark Avatar asked Jul 17 '17 07:07

hashark


People also ask

How do I get values from nested dictionaries?

Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).

How do I query a nested document in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

What is the preferred method of querying embedded documents in MongoDB?

Use the $elemMatch operator to query embedded documents. Use conditional operators to query embedded documents. Use Visual Query Builder to query embedded documents.

How do I search for an object in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

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 :-)

like image 62
hashark Avatar answered Oct 24 '22 21:10

hashark