theGreenCabbage
theGreenCabbage

Reputation: 4845

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.

Upvotes: 15

Views: 15118

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17505

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.

Upvotes: 26

Related Questions