Get an array from the value in an object within an array of objects using Mongoose without using JavaScript

Is there a way to transform the array of objects shown below:

 [{ category:"AAA" },{ category:"BBB" },{ category: "CCC" }]

Into a new format like this: ["AAA","BBB","CCC"] , without relying on filtering or traditional array functions in the backend, but by utilizing MongoDB directly?

Answer №1

db.collection.distinct('category')

This code snippet will return an array containing only unique values for the specified field.

Answer №2

The $map function is used to map the object keys within an array to a new array containing the corresponding key values. Following this, the output is transformed using the $addFields method.


arr = [{ category:"AAA" },{ category:"BBB" },{ category: "CCC" }];
db.collection.aggregate([
    {
        "$addFields": {
            "exclude": {
                "$map": {
                    "input": "$arr",
                    "as": "el",
                    "in": "$$el.category"
                }
            }
        }
    }
])

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

React not correctly returning multiple values in function: TypeError: cannot iterate over undefined (cannot read property Symbol(Symbol.iterator))

Although there are numerous questions with a similar title, none of them address my specific concern. My current project involves a React app that retrieves data from a backend built with Node.js and MySQL. However, I encountered the following error while ...

Unexpected behavior when the coerce method is not invoked as anticipated

My goal is to develop an addition operator for mathematical vectors that allows for adding scalars and arrays to MyVector. It is important for the operation to be commutative, meaning I should be able to add numbers to MyVector and MyVector to numbers inte ...

jinja2.exceptions.TemplateSyntaxError: instead of 'static', a ',' was expected

My current project involves using Flask for Python, and I encountered an error when running the project from PyCharm. The error message points to line 192 in my home.html file: jinja2.exceptions.TemplateSyntaxError: expected token ',', got &ap ...

Struggling to make even the most basic example work with TypeScript and npm modules

After stumbling upon this repository that made using npm modules within a Typescript program look easy, I decided to give it a try by forking it and making some changes. My goal was to add another package to get a better understanding of the process. So, I ...

Could the `<script src="show.js"></script>` code pose a threat?

Upon delivering a webpage, a software engineer included the subsequent line of code towards the end: <script src="show.js"></script> We are uncertain if adding this code to our webpage poses any risks. What could be the legitimate reason behi ...

The function auth.createUserWithEmailAndPassword is not recognized in the context of React

base.jsx: import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; const firebaseConfig = { config }; export const app = initializeApp(firebaseConfig); export const auth = getAuth(); Register.jsx ...

How to integrate a new DOM element into a React Native app with the simple click of a button

Is it possible to add a <Text> element with the click of a button in react native? If so, how can this be achieved? Here is my current code: import React, { Component } from 'react' import { StyleSheet, Text, View, Button } from &apos ...

The gif loader persists even after subscribing

Looking to incorporate the SendGrid subscription widget into my site, but struggling with the implementation. The code provided by SendGrid is partially functional - the loader appears and a success message is displayed upon sign up, but the GIF loader doe ...

Is there a way to update a value in an inner array in MongoDB based on certain criteria using the current value?

I am dealing with a small MongoDB collection that contains arrays of strings. { "_id" : ObjectId("62853dc84409dcc9213f8bca"), "test" : [ "aaaa", "bbb", "ccc" ...

What to do when rows exceed their size limit in an index?

n=[2 5 50]; nn=720; %total number of angles to consider angle=linspace(-2*pi,2*pi,nn); %array of angles S=zeros(1,nn); for j=1:3 z=n(j); for i=1:nn for k=0:z ns=2*k+1; S(j,i)=S(j,i)+(-1)^k*(angle(j,i))^(ns)/factorial ...

Assigning a Value to a Select Option in a Dynamically Generated Form

I've developed a dynamic form that includes a dropdown menu. I would like this dropdown to display fiscal weeks, and to achieve this, I need to implement a loop within a TypeScript function. form.ts - <div class="col-md-9" [ngSwitch]="field.type ...

Declaration of String Arrays

I'm encountering a frustrating problem that should be simple. Java arrays can be quite tricky and not very intuitive. One specific String array I have is called 'title' and it contains various titles. Here is a snippet of the array: p ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Troubleshooting: Javascript success callback not executing upon form submission

A snippet of my JavaScript looks like this: $(document).ready(function(){ $("#message").hide(); $("#please_wait_box").hide(); $("#updateinvoice").submit(function(e){ $("#message").hide(); ...

The ESLint rule "eqeqeq" configuration is deemed incorrect

After successfully running eslint with the provided .eslintrc file, I encountered an issue when making a simple change to use 'standard' instead of 'airbnb-base' as the extend: module.exports = { root: true, parser: 'babel-esl ...

What is the best way to incorporate external HTML content while ensuring HTML5 compatibility? Exploring the different approaches of using PHP, HTML

While this may seem like a simple task to the experts out there, I have been struggling for over an hour without success... My objective is to use a single footer file and menu file for all my webpages while considering blocking, speed, and other factors. ...

Could the Redux store be used to access the state related to specific review comments?

I have a react class component that includes state variables. class NewComponent extends Component { state = { modalIsOpen: false, aa: true, bb: false, cc: false, dd: false, ee: 1, dd: [], cc: [], ff: [], gg: [], ...

What could be the reason for a querySelector returning null in a Nextjs/React application even after the document has been fully loaded?

I am currently utilizing the Observer API to track changes. My objective is to locate the div element with the id of plTable, but it keeps returning as null. I initially suspected that this was due to the fact that the document had not finished loading, ...

Tips for passing multiple arrays to a constructor in Java

I am encountering an issue when trying to pass a multiple array to a constructor. Is this even possible? public class First { public String[] a; public String[] b; public First(String[] a, String[] b){ this.a=a; this.b=b; } } Below is the code sn ...

By default, configure the MUI Collapse component to be in a "collapsed" state

I'm currently working on a React/Next/MUI project and I have a query regarding the default setting for the MUI Collapse element. I would like it to be collapsed by default instead of being opened, especially when dealing with large navigations. Here&a ...