Switching an array with a single string in MongoDB

I'm facing an issue with grouping data in mongoDB and wondering if there's a way to transform an array into a string. The objects included in $lookup are currently displayed in an array format, but I need them in a single string.

Here is my code:


Answer.aggregate([
    {$lookup:
        {
            from: "flashcards",
            localField: "flashcard",
            foreignField: "_id",
            as: "flashcards"
        }
    },
    {$lookup:
        {
            from: "flashcardcollections",
            localField: "flashcards.collectionId",
            foreignField: "_id",
            as: "flashcardcollection"
        }
    },  
 
     
    {
        $group: {
            _id: { collectionName:"$flashcardcollection.name", isPublic: "$flashcardcollection.isPublic" },

            Answers: {$sum: 1},
   
            CorrectAnswers: { $sum: { $cond: [ { $eq: ["$isCorrect", true] }, 1, 0 ] } },
            WrongAnswers: { $sum: { $cond: [ { $eq: ["$isCorrect", false] }, 1, 0 ] } },
            ListOfAnswers: { $push: {date: "$date", isCorrect: "$isCorrect", prompt: "$flashcards.prompt"}}
            }
        },

], function (err, results) {
    statisticsPerCollection.push(results)

   console.log("statisticPerCollection:", JSON.stringify(statisticsPerCollection, null, 2))

}) 
}

The outcome:


[
    {
      "id": {
        "collectionName": "MongoDBG",
        "isPublic": true
      },
      "Answers": 11,
      "CorrectAnswers": 8,
      "WrongAnswers": 3,
      "ListOfAnswers": [
        {
          "date": "2021-03-07T18:47:00.575Z",
          "isCorrect": true,
          "prompt": "MongoDbSize"
        }
...

Desired result: "collectionName": "MongoDBG" instead of "collectionName": [ "MongoDBG" ]

Answer №1

To streamline the process when retrieving a single collection, consider extracting it from the output array of $lookup before proceeding to the grouping stage. This can be achieved by incorporating an additional $addFields or $unwind step for proper formatting of both collectionName and isPublic.

  ...

  {$lookup:
      {
        from: "flashcardcollections",
        localField: "flashcards.collectionId",
        foreignField: "_id",

        as: "flashcardcollection"
      }
  },


  // Implement $addFields
  {$addFields: {
    flashcardcollection: {$arrayElemAt: ['$flashcardcollection', 0]}
  }},

  // Alternatively, utilize $unwind 
  {$unwind: "$flashcardcollection"},


  {$group: {
     _id: {
       collectionName:"$flashcardcollection.name",
       isPublic: "$flashcardcollection.isPublic"
    },
    ...
  },

  ...

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

When getStaticPaths and getStaticProps are programmed to deliver results

Seeking assistance with my first attempt at using getStaticPaths and getStaticProps in nextJS as a beginner. Can anyone help me resolve this issue? const datas = [ { id: 1, name: "Banheiro", image: "https://res.cl ...

Error: The function wrapper.find().simulate('keypress', {key: 'Enter', keycode: 13}) is not working as expected

Let's discuss further about this query vue-btn isn't triggering on pressing the enter key I have designed a sign-in page where users can log in by pressing 'Enter' on the keyboard. Now, I aim to perform a unit test that simulates pres ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

Confusion surrounding the purpose of an AngularJS controller function

After experimenting with some basic tutorials in AngularJS, I came across a discrepancy in how controllers are declared and used. For instance, in this JSFiddle link - http://jsfiddle.net/dakra/U3pVM/ - the controller is defined as a function name, which w ...

Dynamically assigning a name to a variable through code

Is there a quicker way to complete these 100 tasks? variable_1 = 1; variable_2 = 2; variable_3 = 3; ... variable_100 = 100; I attempted to use the following code: for(var i = 1; i <= 100; i++) { variable_ + i = i; } However, I encountered an e ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Troubleshooting problems with anchor-targets in Skrollr

I am experimenting with having divs overlap each other as the page is scrolled using Skrollr. Initially, I was able to achieve the desired effect with two divs. However, when trying to incorporate a third div, only the first and last ones seem to work prop ...

What is causing the addListener function in the events class to malfunction?

I am a beginner in the world of node.js and attempting to execute this piece of code: var eventlib= require('events'); var emitter= new eventlib(); eventlib.addListener('MessageEvent', function() { console.log('Registered the ...

Sending data from Django's render() method to React.js

Currently, I'm working on a Django + React Application project where I am faced with the challenge of passing JSON data from Django's render() function to React.js. To achieve this, I initiate the rendering of an HTML page using Django, with the ...

Checking if multiple text fields with identical names are valid using BootstrapValidator

I'm facing an issue where I am unable to validate multiple text fields with the same name. The validation only works for the first input text field, but not for the rest. <form id = "frm_org_id"> <input type="text" name="email_address[]" pla ...

Generating identical circles using PointsMaterial and CircleGeometry

My goal is to generate circles using two different methods: By utilizing a circle sprite and drawing it with Points and PointsMaterial Using basic circle buffer geometries Unfortunately, I am facing challenges trying to align them due to the size discrep ...

Setting the title attribute for option elements in a select element that is bound to a model using AngularJs

I'm currently working on an HTML select element that is connected to an ng-model. Here's what the setup looks like: <select data-ng-model="accountType" data-ng-options="at.name for at in accountTypes"></select> This is how my accou ...

Is there a way to change the color of the menu button to white if the points are not visible?

I have created CSS to style the menu's color and make the buttons change color based on different actions. However, I also want the buttons to match the colors of the points on the map. To achieve this, I set the background color in JavaScript when ge ...

The mysterious case of the missing currentUserObj in Angular with rxjs Subject

I've encountered an issue while trying to pass data from my login component to the user-profile component using an rxjs subject. Despite calling the sendUser method in the login component and subscribing to the observable in the user-profile component ...

Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled. On a specific page (localhost/admin/networks), I can click on an item from a database-ge ...

A guide to using JavaScript to create a button that can dynamically change stylesheets

Just a heads up, I'm not using classes in this particular scenario. Can't seem to find the answer to this exact question. With javascript, how can I code a button to switch stylesheets every time it's clicked? I've experimented with d ...

In what way does React export a default function that invokes another function within the same file?

Within a JS file in React, I am exporting a default function to App.js. This exported function calls another function that was declared in the same file but was not explicitly exported. How does React know where to find this internal function? Does using e ...

Display/conceal within a jQuery fixed navigation bar (center-aligned)

I am facing challenges with creating a sticky menu that shows/hides with a click button. Considering abandoning the show/hide feature altogether and rebuilding it from scratch in the future. Two major problems I have identified: How can I make the sho ...

Unable to change placeholder in Material UI's Select Form

I'm having trouble modifying my SelectionForm. I need to update the color of the placeHolder image from red to a different color, but I can't find any properties or props on the material ui Docs to do so. Can someone assist me with this? https:/ ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...