16

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.

1
  • Great question! All pymongo tutorials never use a nested key! Commented Feb 16, 2023 at 8:50

1 Answer 1

26

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.

Sign up to request clarification or add additional context in comments.

3 Comments

will this work smoothly even when there are large user datasets?
@galeej Sorry, I haven't used Mongo in 7 years so I'm no longer very familiar with the performance characteristics. I suspect that it will be quite fast as long as the field you're querying is indexed, though.
Very useful answer as PyMongo examples only use a shallow dict

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.