Retrieve a subset of fields from a collection of nested documents

My document looks like this:

{
"_id" : "2",
"account" : "1234",
"positions" : { 
  "APPL" : { "quantity" : "13", "direction" : "long" }, 
  "GOOG" : { "quantity" : "24", "direction" : "long" }
 }
}

I want to retrieve the entire positions object, but only the quantity field, and I want to exclude the direction field. Is there a way to achieve this? Or should I consider using a different schema with an array of objects:

{
"_id" : "2",
"account" : "1234",
"positions" : [ 
  { "name" : "APPL", "quantity" : "13", "direction" : "long" }, 
  { "name" : "GOOG", "quantity" : "24", "direction" : "long" }
 ]
}

Thank you in advance!

Answer №1

When working with the "array" form, all you need to do is specify the field using "dot notation" to access the array member:

db.collection.find({}, { "positions.quantity": 1, })

This query would return:

{
  "_id" : "2",
  "positions" : [
    { "quantity" : "13" },
    { "quantity" : "24" }
  ]
}

If you want to retrieve multiple fields but exclude the "direction" field, you can simply include both fields in the projection:

db.collection.find({},{ "positions.name": 1, "positions.quantity": 1 })

Which would result in:

{
  "_id" : "2",
  "positions" : [
    {
            "name" : "APPL",
            "quantity" : "13"
    },
    {
            "name" : "GOOG",
            "quantity" : "24"
    }
  ]
}

For the "named keys" form, you will need to specify each path individually:

db.collection.find({},{ "positions.APPL.quantity": 1, "positions.GOOG.quantity": 1  })

This query would yield:

{
  "_id" : "2",
  "positions" : {
    "APPL" : {
      "quantity" : "13"
    },
    "GOOG" : {
      "quantity" : "24"
    }
  }
}

Using "named keys" can be cumbersome and inefficient for MongoDB operations, as it requires JavaScript evaluation for traversing keys. This approach is not ideal due to the increased interpreter cost and lack of index optimization for queries. To manipulate output documents using JavaScript expressions, you would need to resort to using mapReduce, which can be impractical for regular operations.

Overall, utilizing an array structure with common paths is generally more efficient and practical than using named keys. Consistent object naming is encouraged for better organization and performance in MongoDB queries.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way I can retrieve data using multiple parameters in Mongoose? I have successfully fetched data based on a date range, but now I need to add another parameter to the query

I'm facing an issue and I could use some help with it. Currently, I am fetching orders using mongoose based on a range of dates. However, I also need to include another parameter that filters orders by both range and if they are considered new. Here ...

Enhance the function for handling AJAX responses

Utilizing this code allows for the handling of responses from an RSS feed. The code efficiently organizes and appends content, separating any embedded videos. While seeking feedback primarily on performance/efficiency, I am also open to other suggestions. ...

Creating a TypeScript class with methods to export as an object

Just dipping my toes into Typescript and I've encountered a bit of a challenge. I have a generic class that looks like this: export class Sample { a: number; b: number; doSomething(): any { // return something } } My issue ari ...

Failure to populate AngularJS view

I am a beginner in AngularJS and I am attempting to create a page similar to the example provided here. While the example works perfectly when copied from the link above, I am facing difficulties trying to integrate it into my folder structure as displaye ...

Encountering a 304 status error in the HTTP GET response after deploying a React app on Netlify

After deploying my react application on Netlify, I used the npm run build command to create the local scripts and manually deployed them in production mode on Netlify. The build scripts were generated on my local machine and then uploaded to the Net ...

Sorting through elements in an array - MongoDB

I am new to working with mongodb and I have a question about setting up a mongoose schema to add indexed items to an array. My desired output format is: _id: some_id users: Object 0: Array 0: some_user_id 1: some_user_id 2: some_user_i ...

Issue: The error message "undefined variable 'angular'" appears when attempting to access offline files stored on a network drive

I have successfully developed offline forms using angular js v1.6.4, angular-ui-bootstrap, and angular-ui-router without the need for server hosting. When the package is saved on local storage, it functions perfectly on both IE and Chrome browsers. Howeve ...

Transform the JavaScript onclick function into jQuery

I have been working on incorporating my javascript function into jQuery. The functionality I am aiming for is that when you click on a text (legend_tag), it should get added to the textarea (cartlist). <textarea id="cartlist"></textarea& ...

Having trouble accessing an injector service within the promise of a dynamically loaded JavaScript function that has been assigned to a global variable

Query I am facing an issue while trying to integrate PayPal with Angular. I am encountering difficulties when attempting to call an injected service inside a function of the promise returned. Any assistance in resolving this would be greatly appreciated. ...

$http({method}) is malfunctioning while $http.get is functioning properly

Issue Description: While working on my project, I encountered an issue where using $http({ method : 'GET', url : data : ..... param works fine for both GET and POST requests. However, when the same method is used in JSFiddle, it blocks my reques ...

Connecting Vue.js components together

I have two separate components - one for viewing data and another for editing the same data. The viewing component contains labels and paragraphs, while the editing component includes inputs and textareas. Both components are fed the same data object. Is ...

How can you utilize Javascript to retrieve an element by its inner text within the HTML tags?

As a novice, I have been struggling to find the solution to my question even after extensive searching. In the scenario at hand, I am specifically interested in locating the following element: <a href="bla" onclick="dah">some text here</a> I ...

Issues with Angular functionality

I'm a newcomer to Angular and I am trying to recreate this example from jsfiddle in order to experiment with nodes. However, I am encountering issues with the Angular setup. Firstly, the jsfiddle is causing confusion because the application names do n ...

What's the CSS equivalent of Java's window.pack() method?

I'm relatively new to css and I'm attempting to create a border around a <div>. My goal is for the border to be limited to the size of the elements inside the div and adjust dynamically in proportion to any new objects that may appear or di ...

The Angularfire library encountered an issue when trying to access the 'push' property of a null object

I am currently in the process of creating a new object in the database for an assessment. Right now, I have hardcoded it to test its functionality, but ultimately, it will be dynamic based on user input from the view. However, I am encountering an error th ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

Text To Appear Gradually When Button Is Clicked

Is it possible to create a fading effect for text when a button is clicked? Currently, my code displays some text as block while hiding the rest with display:none. Take a look at my JavaScript code: <script> //Select button by id const btn1 ...

Erroneous deletion issue in React list causing removal of incorrect item

While working on creating a todo list in React, I faced an issue when trying to implement a delete function. The problem arose when attempting to delete an item - instead of removing the selected item, React ended up deleting everything except that specif ...

Employing the `instanceof` operator on instances generated by constructors from complex npm dependencies

Context: In one of my npm modules, I've implemented error handling code with a custom error type called CustomError: function CustomError () { /* ... */ } CustomError.prototype = Object.create(Error.prototype); CustomError.prototype.constructor = Cu ...

Discover the process of loading one controller from another controller in Angular JS

Is it possible to load an entire controller1 from a different controller2, not just a function? ...