Combine sub-documents with missing information

In my mongoDB collection, the data structure includes:

{
    "_id" : ObjectId("..."),
    "records" : [
        ISODate("2020-04-19T00:49:18.945Z"),
        {
            "_id" : ObjectId(""),
            "date" : ISODate("2020-05-07T04:49:55.643Z"),
            "text" : "someText"
        }
    ],
}

Due to version upgrades, the content in records varies.

I am looking to aggregate records.text from all documents while disregarding any missing data. I attempted to use code shared on MongoDB: Aggregate and flatten an array field

db.collection.aggregate({$unwind : "records"},
                      {$project: {_id: 1, 'text': '$records.text'}})

However, this resulted in the following error message:

The path option to $unwind stage should be prefixed with a '$': records

I then tried to rectify the error based on instructions provided in these directions, aiming to handle empty fields:

db.collection.aggregate({$unwind : "records", includeEmpty: false},
                      {$project: {_id: 1, 'text': '$records.text'}})

Yet,d this resulted in another error:

A pipeline stage specification object must contain exactly one field.

How can I effectively aggregate values from nested arrays that may have empty elements?

Answer №1

If you want to exclude the empty records, you can utilize the $exists operator:

db.collection.aggregate([
    { $unwind: "$records" },
    { $match: { "records.text": { $exists: true } } },
    { $project: { _id: 1, text: "$records.text" }}
    {$group: {_id: "$text", count: {$sum: 1}}},
    {$sort: {count: -1}}
])

Check out this example on Mongo Playground

Answer №2

When constructing your initial query, make sure to include the '$' before 'record' as it represents a field value. The corrected version of the query would look like this:

db.collection.aggregate({$unwind : "$records"},
                      {$project: {_id: 1, 'text': '$records.text'}})

Hopefully, this adjustment resolves your issue.

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

Is it possible to rearrange the positions of 2 divs using solely CSS?

I have created a unique design. On iPad, I am assigning the class 'handHeld' to the <body>, which will trigger positional changes between optionsWrapper and #container using CSS classes I've defined below on jsfiddle.net. .handHeld d ...

Convert a Material UI dropdown into a Bootstrap dropdown

The reason for this transformation is due to the unsightly appearance of the dropdown from Material UI. Despite that, the code is functioning properly. It features a dropdown with multiple choices, loading a list of strings and their corresponding images. ...

Sorting two different divisions is an example

I need advice on how to toggle between two divs, A and B, without having to reload the page. Ideally, I would like to have three buttons - one that shows only div A when clicked, another that displays only div B, and a third button that shows both A and ...

Initiating Database Countdown (date)

My goal is to create a live countdown timer that updates based on the date retrieved from a MySQL database, without the need for manual refreshing. Here's the code snippet: <?php $date = strtotime($row_tournaments['date']); $re ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

Creating a dynamic mouse trail effect using CSS and JavaScript without compromising element clickability

I'm looking to create a mouse trail that follows the cursor as it moves, made up of small icons or images that gradually fade out over time. I attempted to achieve this by overlaying a grid on top of all other elements on the page. The grid consists o ...

Encountering a Null Pointer Exception when trying to locate an element on an AngularJS website using Selenium

Testing an AngularJS website with Selenium can be challenging due to angular directives, as mentioned in a blog. Despite encountering some stability issues such as failures and exceptions like "unable to locate Element," "No such element," or "Null pointer ...

Guide on Importing All Functions from a Custom Javascript File

As a beginner in learning Angular, I am faced with the task of converting a template into Angular. However, I am struggling to find a solution for importing all functions from a custom js file into my .component.ts file at once. I have already attempted t ...

Custom tooltip in Chart JS is not displaying as expected

I have created a line graph and I am looking to customize its tooltip. When hovering over the graph, I want it to display the following information: Question: This is question 1 Your answers: 3 Average answers: 7 Your average: 5 Average: 7 The data in th ...

Add the user's input text to a modal in C# MVC 5

If my status changes, I want to add another text box or text area for additional comments. In the photo provided, this has been implemented but the positioning is not quite right due to issues with the modal. Below is a snippet of my code where you can ta ...

As the text is being selected within a react-rnd, once the selection extends outside of the draggable component, the selected text will automatically adjust

I've encountered an issue with a draggable textarea created using react-rnd. The problem arises when I try to select text within the textarea, and accidentally move my cursor outside of the react-rnd component, causing the selection to change unexpect ...

Create a div element that can be expanded on smaller devices

Is it possible to expand a div while hovering on a small or x-small device? I want to achieve something like this: https://i.sstatic.net/doJKa.png Currently, I can only hide the yellow div when the page is displayed on a small device. I am looking for a ...

The persistent presence of the Dropup Bootstrap class ensures that it remains active and visible at all

The dropdown-item class functions correctly only when used with the dropdown class, but does not work with the dropup class. The dropup feature fails to function after clicking on all submenu items. This is because all dropdown-items become active and v ...

Using JQUERY to toggle classes conditionally

$('.showall').css("cursor","pointer").click(function() { $('.value-container').toggle(); $('.dim-header').toggleClass($('.dim-header').toggleClass() == 'dim-header' ? 'dim-header active' : & ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...

What could be the reason for the lack of change in my innerHTML object after assignment?

I am facing an issue with my HTML file where I have a header and 2 buttons underneath: <h4 align="center">August 2014</h4> <img src="images/arrow_BW_thin_left.png" alt="Previous Month" id="left" onMouseUp="funcLeft()" style="cursor:pointer" ...

What is the best way to display two timers on one page?

I'm having an issue with displaying two timers for a 3-minute countdown. The problem is that the second timer works perfectly, but the first timer doesn't. Even if I remove the second timer, there is still some problem with the first one. The cod ...

Utilizing raycasting for accentuating a line of 3D objects in a three.js

I'm currently working on using raycaster to detect a row of 3D cubes for highlighting and coloring upon mouse hover. I've been following the guidance provided in this post Change color of mesh using mouseover in three js. However, I've encou ...

Storing information while navigating with react routers

I am working on a project where I need to create multiple pages with forms. As the user navigates from one page to another, I want the data they entered to be saved automatically in the state of that component. The user has not submitted anything yet and t ...

issues with search functionality in angular

Just diving into the world of angular and struggling with implementing a 'live search' functionality. I've stored my JSON data as a variable in a JavaScript file and successfully displayed it in the HTML. I also have a 'list' radio ...