"Exploring the depths of MongoDB: Unraveling multiple criteria search

I have a diverse collection of food entries like this

foods{
{ 
  name: 'rice'
  type: 'Brazilian'
},
{
  name: 'meat'
  type: 'Spanish'
}
,
{
  name: 'Cake'
  type: 'Brazilian'
}

How can I retrieve a specific number of foods for each type in MongoDB? For instance, I want to get a collection (array) of 4 foods for each type.

[
    [
        {
            name: 'rice'
            type: 'Brazilian'
        },
        {
            name: 'meat'
            type: 'Brazilian'
        }       
        {
            name: 'pizza'
            type: 'Brazilian'
        },
        {
            name: 'bread'
            type: 'Brazilian'
        }
    ],

    [
        {
            name: 'beans'
            type: 'spanish'
        },
        {
            name: 'fish'
            type: 'spanish'
        }       
        {
            name: 'chocolare'
            type: 'spanish'
        },
        {
            name: 'ham'
            type: 'spanish'
        }
    ]

]

Answer №1

To achieve the desired outcome, utilize aggregation techniques. Within your aggregation pipeline, the $group operator plays a central role in shaping the result by grouping documents from the input collection based on the type key. Subsequently, you can employ an accumulator operator like $push to construct an array. Consider the following example:

var pipeline = [
    {
        "$group": {
            "_id": "$type",
            "items": {
                "$push": { "name": "$name", "type": "$type" }
            }
        }
    }
]

var result = db.products.aggregate(pipeline).map(function (item){ return item.items });
printjson(result);

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

What is the process for including parameters in a javascript/jquery function?

This unique script enables you to click on a specific element without any consequences, but as soon as you click anywhere else, it triggers a fade-out effect on something else. Within the following code snippet, you can interact with elements inside $(&apo ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...

The form is refusing to submit even after using the "return false

Even after adding validation to the form, it still submits when the script returns false. The Form Submission <form action=payment.php method=POST name=UserForm id=UserForm onsubmit="return check(this); return false;"> Javascript Code function ch ...

Stop the duplication of downloading JavaScript files

When it comes to my website, I have incorporated sliders that stream videos from Vimeo. Upon running a check on GTMetrix, I noticed an overwhelming number of http requests. Looking at the waterfall, I discovered numerous duplicate downloads of javascript, ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...

Using C# Lambda Expressions to Traverse Nested Objects

In my current project, I have a JSON data that has been de-serialized into a C# object. My goal is to extract the values of INFO_CARD_ID, DOCUMENT_NUM, and REVISION_NM during each iteration process. { "result": { "message": ...

Arranging an array of objects by a specific property in an Angular controller with the help of $filter

In my data set, there is an array of objects referred to as $scope.segments, which looks like this: [ { "_id": "55d1167655745c8d3679cdb5", "job_id": "55d0a6feab0332116d74b253", "status": "available", "sequence": 1, "body_original": " ...

Verify the existence of an array element and proceed to the next one in JavaScript if it does not

I am attempting to select 3 random answers from an array of possible answers and store them in a new array. The new array, selectedAnswers, should contain 3 random answers along with the correctAnswer. While I have made some progress, I am facing an issue ...

JavaScript / Regular Expression: remove the initial <p> tag if it meets a specific condition

Whenever I receive HTML content from the API, it may come in different formats. Sometimes, it looks like this: <p>::type/12</p> <p>Some content</p> <p>Some more content</p> Other times, it might not have the first para ...

Exploring Mongoose: A Guide to Populating Data from a Parent to a Child

I'm currently diving into the world of mongoose, where I have set up 3 collections (User, Post, Comment), each with its own unique schema: User { fullName: String, email: String, } Post { author: {type: mongoose.Schema.Types.ObjectId, required ...

Create an Angular directive that highlights a div if any of its child inputs have focus

I've developed an Angular directive for a repetitive section containing form elements. My aim is to have the entire section highlighted whenever any input field inside it is focused. template.html <div class="col-md-12 employee-section"> <l ...

The term "GAPI" has not been declared or defined within the Svelte

Encountering an issue while trying to incorporate the Youtube data API into my Svelte application. Upon loading the site, the error message displayed is: Uncaught ReferenceError: gapi is not defined Reviewing the relevant code reveals: <svelte:head> ...

The attempt to use RTSP streaming with Node.js for an IP camera and JSMPEG

Having an issue connecting to an IP camera where the image does not appear properly When running node app.js "frame= 1970 fps=2.0 q=7.6 size= 22457kB time=00:16:25.00 bitrate= 186.8kbits/s dup=0 drop=3 speed=1.01x" Upon executing index.html &qu ...

Challenges integrating Jquery with Flask

When attempting to add an HTML element using jQuery, I encountered an exception from Flask: jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'static' The string seems correct, but I'm unsure about what the issue ...

Is there a more efficient method for managing Express rendering based on whether the request is an AJAX post or an HTML form submission?

Currently, I am working on an HTML form and incorporating jQuery's AJAX post feature to retrieve information based on the success or failure of a database insertion. Within my code, I have set the ajax post variable to true when utilizing AJAX postin ...

Where exactly is the JSON data stored after I receive it through an AJAX request?

I am curious about where certain JSON data is stored when it is sent from the server to the client, especially when they reside in different directories. Currently, I am working on developing a simple API that sends JSON data from the server (port number: ...

Issue with List<Object> formatting in JSON is not working as expected

Currently, I am retrieving data from a ResultSet and storing it in a list: ResultSet resultSet = stmt.executeQuery(sql); List<Object> res = new ArrayList<>(); while(resultSet.next()){ res.add(resultSet.getObject(1)); } return res; ...

Load various information retrieved from an HTTP API into a SQLite database

I am currently working on an Ionic2 project that requires users to log in before gaining access to the system. Once the login is successful, I need to post their username to another API to retrieve a list of all entries made by them. The challenge I am fac ...

disableDefault not functioning properly post-fadeout, subsequent loading, and fade-in of new content with a different URL into

After extensive searching, I still haven't found a solution to my problem. My task involves bringing in HTML pages into a div element. I managed to make the content fade out, load new href content, and then fade in the new content. However, I'm ...

A step-by-step guide on implementing a callback function

I am eager to incorporate a callback into this script - specifically the third callback onSlideChangeStart(swiper) found at http://idangero.us/swiper/api/#.V9CMp5grJlY. Since I have never worked with callbacks before, I am unsure of where to begin. In es ...