Get nested fields with MongoDB shell Get nested fields with MongoDB shell database database

Get nested fields with MongoDB shell


For the document above, the following find() query would extract both the "nickname" of the document, and its associated "arrangeable_values" (where the document is in the users collection):

db.users.find({}, { "nickname" : 1,  "watchlists.arrangeable_values" : 1 })

The result you get for your single document example would be:

{ "_id" : ObjectId("4f6c42f6018a590001000001"), "nickname" : "superj", "watchlists" : [         {  "arrangeable_values" : {    "description" : "My introduction presentation to node.js along with sample code at various stages of building a simple RESTful web service with journey, cradle, winston, optimist, and http-console.",     "tag" : "",     "html_url" : "https://github.com/indexzero/nodejs-intro" } },        {  "arrangeable_values" : {    "description" : "A Backbone alternative idea",  "tag" : "",     "html_url" : "https://github.com/maccman/spine.todos" } } ] }


MongoDB queries return entire documents. You are looking for a field inside an array inside of the document and this will break the find().

The problem here is that any basic find() query, will return all matching documents. The find() does have the option to only return specific fields. But that will not work with your array of sub-objects. You could returns watchlists, but not watchlist entries that match.

As it stands you have two options:

  1. Write some client-side code that loops through the documents and does the filtering. Remember that the shell is effectively a javascript driver, so you can write code in there.
  2. Use the new aggregation framework. This will have a learning curve, but it can effectively extract the sub-items you're looking for.