Exploring MongoDB: Filtering Array Elements in a Project

In my current aggregation setup, I am using the following simplified code:

Model.aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer',
        as: 'orders',
      },
    },
    {
      $project: {
        openOrders: {
          $filter: {
            input: '$orders',
            as: 'order',
            cond: { $eq: ['$$order.status', 'open'] },
          },
        },
      },
    },        
  ])

This code returns a structure that looks like this:

{
  _id: ...,
  openOrders: [
    [Object], [Object]
  ],
}

The `[Object]` entries are simply the full objects retrieved from the database with all their properties intact.

My goal is to modify the output so that only the `_id` fields of these objects are returned:

{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}

UPDATE: Ideally, I would like the final result to look like this:

{
  _id: ...,
  openOrders: [
    { _id: ... },
    { _id: ... }
  ],
}

I have attempted to add an additional `$project` stage at different points in the aggregation pipeline without success. If anyone has any suggestions on how to achieve this, your help would be greatly appreciated.

Answer №1

To enhance your query, include a $project stage similar to the following:

{
  $project: {
    openOrders: 'openOrders._id'
  }
}

This adjustment will result in an output like:

{
  _id: ...,
  openOrders: [
    _id1,
    _id2,
    ...
  ],
}

instead of

{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}

I recommend this type of querying because when you look at the openOrders field, it consists solely of _ids within an array. Thus, having only one _id field inside the array doesn't make sense.

If you still prefer the output to be an array of objects, you can utilize the following approach:

{
  $project: {
    'openOrders._id': 1
  }
}

Answer №2

To achieve an array of _id's structured like this

openOrders: [ _id: ..., _id: .... ]

and not an array of _id's within objects :

openOrders: [ {_id: ...}, {_id: ....} ]

You should utilize $reduce instead of $filter :

Take a look at the query below:

 db.collection.aggregate([
    {
      $project: {
        openOrders: {
          $reduce: {
            input: "$orders",
            initialValue: [],
            in: { 
              $cond: [ { $eq: [ "$$this.status", "open" ] },
                { $concatArrays: [ "$$value", [ "$$this._id" ] ] },
                "$$value"
              ]
            }
          }
        }
      }
    }
  ])

Try it out here: mongoplayground

Note: When dealing with JavaScript and printing JSON with objects, remember to use JSON.stringify(yourJSON) to avoid displaying [Object], [Object] on the console.

Update:

If you require an array of objects with the field _id, simply add another $project stage at the end. However, using $reduce is recommended for your situation to get an array:

{ $project: { "openOrders._id": 1 } } // extracts `_id` fields from each object

Test it here: mongoplayground

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

How to resolve 404 error for HTML files in Angular 4's "basic deployment" strategy?

I have been attempting to deploy my application following the instructions in the "Simplest deployment possible" section of the angular guide. Starting from a project created using the quick start setup, I made changes to the files index.html, main.ts, and ...

Executing operations on subdocuments in Mongoose without having to fetch the parent

Currently, when I need to delete a subdocument, I follow this process: Post.findById(post_id).exec(function(err, post) { post.comments.remove({'_id': comment_id}); post.save(function(err) { res.end("Success!"); }); }); This method doe ...

Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read. For reference, something similar can be seen on this site. I have created my custom progress bar and coded it on fiddle, whe ...

Querying a MongoDB collection based on date values

We currently manage a substantial MongoDB database with 70 Million records. Each day, roughly 1 Million new records are added to this database. Each document within the collection contains the following information: { "_id" : ObjectId("5447f506e4b081e ...

What is the best way to highlight a specific city on a map by placing a circle around it?

I am currently developing a project that involves creating a circle around the location of an item on a Google Map. In the code snippet below, when the show tab is clicked, it should display a circle around the item's location on the map: <div cla ...

What are the steps to effectively utilize <ul> for showcasing scrolling content?

I stumbled upon and found it to be a great inspiration for my project. I tried replicating the layout of the listed items on the site: .wrap { display: block; list-style: none; position: relative; padding: 0; margin: 0; border: ...

Having trouble inserting data into both MongoDB and MySQL databases using CodeIgniter?

I am in the process of creating a REST API server, taking inspiration from https://github.com/chriskacerguis/codeigniter-restserver. I am utilizing both Mongo and MySQL databases to store the API responses. The issue I am facing is that while I am able to ...

My React JS page suddenly turned blank right after I implemented a setState() function within my functional component

I was working on my code and everything seemed fine until I tried to incorporate the setState function with setcategory and setvalue. However, after making this change, my react page suddenly went blank. Can anyone help me identify what went wrong and pr ...

What steps should be taken to avoid an event from occurring when an error message is encountered?

I have a dropdown list of cars where an error message is displayed if any of them becomes inactive. When the error message is shown, clicking on the Route Car button should prevent any event from occurring, i.e., no modal popup should be displayed. How ca ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Issue with infoWindow flickering and closing automatically on Google Maps API due to a mouseout event-triggered action

Currently, I am working on a project where I am creating polygons. The issue I am facing is that whenever the infoWindow is hovered over, the mouseout event on the polygon is triggered. I would like to prevent the mouseout event from firing unless the mo ...

Tips for reducing the minimum height and weight of a GridStack grid component

Currently, I am utilizing the GridStack.js library and facing an issue with implementing keyboard functionality. When I decrease the screen width (using Chrome DevTools) to less than 800-1000px, all the grid elements automatically adjust their width to 100 ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...

Utilizing JodaTime with JavaScript (AngularJS): A Comprehensive Guide

I am utilizing DateTime to create Date objects and sending them as JSON to the UI. How can I work with this in JavaScript (specifically AngularJS) and convert it back and forth? For instance, if I need the user to update the time, I should be able to retr ...

Having issues with "return false" not functioning properly in jQuery ajax calls

I have been developing a registration form using jQuery ajax. Below is the code snippet I am working with: function validateData() { var email = jQuery("#email").val(); var username = jQuery("#username").val(); var emailReg = /^([\w-&bsol ...

Importing external scripts using requirejs without access to the configuration

I'm currently facing an issue with loading the datatables javascript library within a plugin I'm developing. The problem arises when attempting to load the external resource, as there seems to be a conflict with datatables when I trigger the requ ...

Angular ng-boostrap modal automatically refreshes upon detecting mouse movement with an embedded video

Currently, I am facing an issue with my Angular 7 ng-bootstrap modal. The problem arises when the modal, which includes a video player within an <iframe>, is moved to the production system. Whenever there is any mouse movement detected, the video get ...

Update the HighChart Pie chart depending on the selection in the dropdown menu

Currently, I am working on creating a pie chart using data retrieved from a web socket in JSON format. Once the JSON object is returned, if the user selects the "Pie Chart" option, another Select dropdown will be displayed to choose a specific time period. ...

Is an empty string equivalent to false in a boolean context?

I would appreciate further clarification on this subject. I have read several articles, but none have fully answered my questions. ...

Tips and tricks for sending variables to an iFrame using jQuery functions

My goal is to dynamically change the source, width, and height of an iframe based on the link that is clicked. Currently, I am able to fire the iframe with hardcoded values using the following code: This is what works: $('.myLink').click(functi ...