retrieve the item that contains a vacant array within a specific record

I have a set of nested object documents that I need to retrieve and group based on the nested objects with empty arrays using aggregation.

Let me provide a more detailed explanation-- suppose my collection consists of the following documents --

Document 1

{
    "_id": "17202155",
    "completed": [
      "cse331",
      "cse312"
    ],
    "incompleted": [
      {
        "name": "math",
        "preReq": []
      },
      {
        "name": "science",
        "preReq": [
          "bang",
          "eng",
          "math"
        ]
      },
      {
        "name": "astronomy",
        "preReq": [
          "bang",
          "eng",
          "science"
        ]
      }
    ]   
}

Document 2

{
    "_id": "17202157",
    "completed": [
      "cse331",
      "cse312"
    ],
    "incompleted": [
      {
        "name": "math",
        "preReq": []
      },
      {
        "name": "science",
        "preReq": []
      },
      {
        "name": "astronomy",
        "preReq": [
          "bang",
          "eng",
          "science"
        ]
      }
    ]
}

I aim to fetch the documents grouped by ID where the object contains an empty array. This would result in the following output --

{
    "_id": "17202155",
    "incompleted": [
      {
        "name": "math",
        "preReq": []
      }
    ]
},
{
    "_id": "17202157",
    "incompleted": [
      {
        "name": "math",
        "preReq": []
      },
      {
        "name": "science",
        "preReq": []
      }
    ]
}

I attempted to use the provided code, but it didn't work. Being new to MongoDB, I request your assistance--

#my code-

db.collection.aggregate({
  "$unwind": "$_id"
},
{
  "$group":{"_id": "$incompleted",}
},
{
  "$match": {
    "_id.preReq": {
      $size: 0
    }
  }
},
)

Answer №1

db.collection.aggregate([
  {
    $unwind: "$incompleted"
  },
  {
    $match: {
      "incompleted.preReq": []
    }
  },
  {
    $group: {
      _id: "$_id",
      incompleted: {
        $push: "$incompleted"
      }
    }
  }
])

Check out the result on 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

Issues with message display validation in jQuery

Validation has been applied to the form, and there are div elements within the input fields with corresponding IDs. The goal is to display error messages within those divs. Specifically, if an input field is missing, the errorMessage should be set in the ...

Typescript generates a warning when utilizing JSON objects in conjunction with data types

Attempting to access the attributes of a JSON object within a hook using bracket notation. Although it seems to be functioning correctly, TypeScript continues to throw this warning: Property 'github' does not exist on type 'PropertyValues& ...

Iteratively traverse the object to establish connections between parent and child elements

I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents ...

Understanding the Vue lifecycle methods for updating Vuex state

Utilizing Vue and Vuex components, the code within my component consists of: computed: { ...mapState({ address: state => state.wallet.address }) }, The functionality operates smoothly in the user interface. However, my objective is to invoke a ...

Is it necessary to use JS/JQ to trigger PHP form data?

Can PHP files/functions be executed without reloading the page? It can be quite disruptive when developing a chat app and every time you send a message, the entire page refreshes. I attempted to use AJAX but it didn't work. Is it not possible to send ...

Ajax request terminated while sending parameters

Trying to redirect to http://google.com using an ANCHOR tag, while also posting parameters to another page via AJAX is causing the POST request to be aborted even though the redirection is successful. Here is the code snippet: <script type="text/ja ...

Encountering CORS Issue when attempting to upload a file from an external URL using Angular

I am attempting to upload a file from an external URL, but I keep encountering a CORS error when trying to access the external URL. await fetch(url).then(function (res) { response = res; }).catch(function () { setTimeout(() => { this.toaster. ...

Using DraftJS to swap text while preserving formatting

Currently, I am implementing Draftjs with draft-js-plugins-editor and utilizing two plugins: draft-js-mathjax-plugin and draft-js-mention-plugin My goal is to replace all mentions with their corresponding values when the user uses '@' to mention ...

Retrieving the correct selected value from multiple select tables created through a for loop can be achieved using JavaScript or jQuery

Despite searching Google and asking previous questions, I have not found a solution that addresses my specific issue. The common responses only pertain to one select element with multiple options. To further clarify, when I create code for a loop to genera ...

How can I make the columns in Next.js / Tailwind expand horizontally first instead of vertically?

Recently, I decided to customize the Next.js Image Gallery starter for some hands-on experience in full stack development with Next.js. My goal was to create a chronological photo gallery of a recent trip, but encountered an issue where the responsive colu ...

Safari failing to display Arc on 2D context

When attempting to draw a simple circle on a canvas, everything works smoothly in Chrome but encounters issues in Safari. What's puzzling is that even though I can retrieve the x position of the circle as expected, it simply fails to render correctly ...

What is the most effective method for organizing an object by its values using multiple keys?

I'm interested in utilizing the sort method mentioned in the link but I am facing { "CYLINDER": 2986, "HYDRAULIC": 1421, "JACKS": 84, "INSTALLATION": 119, "REAR": 61, "JACK": 334, "TUBE": 1, "FEED": 114, "ASSEMBLY": 326, "DCS": 2 ...

Troubles with Vue.js when retrieving URL data from API

How can I properly display multiple store URLs from an API in separate lines? Here is my vue code: <a v-bind:href=“storeUrl”> {{storeUrl}} </a> And here is my script: .... computed:{ storeUrl() { return this.games.store.map(({{url}}) => ...

What is a more efficient way to avoid duplicating code in javascript?

Is there a way to avoid repeating the same code for different feeds? I have 8 feeds that I would like to use and currently, I am just incrementing variable names and feed URLs. <script type="text/javascript> function showFeed(data, content ...

delete content of file in vue 3

I have a Vue 3 component that looks like this: <template> <input type="file" :class="inputClass" accept=".pdf" @input="onFileSelect" ref="fileInput"> </template> <script> import ...

What is the best way to prevent a router.post in Express from interrupting an earlier call to the same route?

In the environment I am working in, there is an Angular front end paired with an Express/Nodejs backend. One issue I have encountered is when a user triggers a long running SQL process by clicking a button on a web page. This process is initiated through ...

How can I ensure that my user responses are case-insensitive?

Currently, I'm facing a roadblock in my coding journey. I am trying to modify my code so that user responses are not case sensitive when compared for correctness. Can anyone offer some advice on how to achieve this? Check out the code snippet below: ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Using AngularJS ui-router ui-sref results in the error message "Uncaught TypeError: Cannot read property '0' of undefined."

I am currently working on an angularJS component that utilizes ui-router with 2 straightforward route states. export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('details', { ...

Resolve feature for UI routes fails to function upon refreshing the page

My app utilizes UI Route for view routing. When accessing /berlinerliste/, a function is triggered to display an array of objects. If one of these objects is clicked, the view changes to /berlinerliste/{id}/ and shows the details of that specific object. ...