Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using find() to search for nested keys in MongoDB

This is going to be a silly question, but if I have a Mongo object that is in this format:

{
    "url": "google.com",
    "statusCode": 301,
    "headers": {
        "location": "http://www.google.com/",
        "content-type": "text/html; charset=UTF-8",
        "date": "Fri, 22 Mar 2013 16:27:55 GMT",
        "expires": "Sun, 21 Apr 2013 16:27:55 GMT",
        "cache-control": "public, max-age=2592000",
        "server": "gws",
        "content-length": "219",
        "x-xss-protection": "1; mode=block",
        "x-frame-options": "SAMEORIGIN"
    }
}

Using db.collections.find(), how do I find the server key, or any key that is nested within another key?

I have tried db.collections.find({headers:{server:"gws"}})

I have tried quoting them in all possible combinations, but the output has always been blank, or ...

Any suggestions would be appreciated.

like image 929
theGreenCabbage Avatar asked Mar 22 '13 16:03

theGreenCabbage


People also ask

How do I find nested objects 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 does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do I create a nested query in MongoDB?

MongoDB Nested Query Match on a Nested Field You can use the dot notation (“field. nestedField”) to specify query criteria for fields in embedded/nested documents. For queries that use dot notation, fields and nested fields must be enclosed in double-quotes.


1 Answers

You have to use dot notation to get what you're looking for. It would look like:

db.collections.find({"headers.server":"gws"})

In your query, what you're asking for is documents where headers is an object that looks like {server: "gws"}, so that only work if you know what the entire subdocument is.

like image 103
Aaron Dufour Avatar answered Oct 11 '22 09:10

Aaron Dufour