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.
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.
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With