The intricate depths of MongoDB's nested aggregation capabilities

Summary:

Current Data:

db.posts.find()

[ 
  { authorId: 1, 
    text: "lorem",
    likes: 22 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 8, commentText: "trash"}
    ]
  }, 
  { authorId: 2, 
    text: "ipsum",
    likes: 33, 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 1, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
  { authorId: 3, 
    text: "ipsum",
    likes: 44, 
    comments: [
      { commentatorId: 2, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
  { authorId: 1, 
    text: "ipsum",
    likes: 55, 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
]

Desired Outcome:

{ 
 1: {posts: 2, likes: 77, comments: 4}, 
 2: {posts: 1, likes: 33, comments: 4},
 3: {posts: 1, likes: 44, comments: 3},
 8: {posts: 0, likes: 0,  comments: 1},
}

The challenge here is to aggregate data based on authorId and commentatorId fields which are linked to another collection (named "users"). Every user should be included in the result regardless of whether they have posted any content. The count for comments should include all posts, not just ones where authorId is equal to commentatorId.

Answer №1

I believe this could be of interest to you

db.posts.aggregate([
{$unwind:"$feedback"},
{$group:{_id:"$userID", 
"reactions":{$addToSet:"$reactions"}, "feedback":{$addToSet:"$feedback"}}},
{$project:{"reactions":{$sum:"$reactions"}, "posts":{$size:"$reactions"}, "comments":{$size:"$feedback"}}}
])

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

Tips for querying multiple elements that share a common ID and verifying if the input has been modified

I have a series of text inputs that share a common id prefix but differ slightly at the end. Whenever a user enters text in any of these input fields, I want to trigger a function. Currently, I have this functionality implemented with the following code: ...

Looking to retrieve a cookie within Vue Router in Vue 3? Utilize the following approach within your router's `index.js

Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests. I am in the process of implementing a route guard to ...

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...

Setting up a service in angularjs that is reliant on another service

One thing I'm trying to figure out is how to utilize a service like $http outside of the $get function. Is this even possible? Currently, my code loads a json file that contains a dictionary used by my application in various ways. I want users to have ...

Unexpected firing of jQuery blur event upon page load rather than during the expected time

Currently, I am working on a project that involves form validation using jQuery. One element I am focusing on is the email field, where users will input their emails. I want to ensure that the email input is checked once it has been filled out. My initial ...

Verify changes in the Cross Domain RSS feed by utilizing Ajax technology

I have a website where I am trying to automatically reload an RSS news feed from every 60 seconds if it has been updated. I attempted to use Ajax for this purpose, but I seem to be facing some issues: <script type="text/javascript" src="../js/jquery.a ...

"Troubleshooting issue: Popup in react-leaflet fails to display upon clicking

Currently, I have integrated react-leaflet into my ReactJS application to dynamically create markers with popups. However, when implementing the code as shown below, the popup box fails to display and an error message appears in the web developer console. ...

Conceal or reveal form elements based on input selection

In my current HTML form generated by PHP, I have multiple instances of the following structure: function show(elem, show){ var elements = elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden"); var i; for(i=0; i<eleme ...

The CSS navigation bar is not properly aligned in the center

This menu was constructed by me: JSBIN EDIT ; JSBIN DEMO Upon closer inspection, it appears that the menu is not centered in the middle of the bar; rather, it is centered higher up. My goal is to have it positioned lower, right in the middle. I ...

Re-activate video playback after 30 seconds of user inactivity (using RxJs)

My intention is to provide a brief explanation of the functionality I am looking for. Essentially, when a video is playing, I want it to pause if a user clicks on it, allowing them to do something else. Then, after 30 seconds of idle time, I need the video ...

Node.js web application encounters ECONNRESET and MongoNetworkError issues

Currently working on a website with Node.js, Express, and MongoDB (MLAB). The code is too long to post here. When I try to access my index page, app.get("/alumniport", (req, res) => { alumni.find((err, theAlumni) => { if (err) { res.redi ...

Maintain Collection Privileges Remain Effective Even Upon Revocation

After creating a role and assigning find and insert permissions only, I realized that the user could still create new collections on their own. Despite revoking CreateCollection access, this issue persisted. 1. Access the app database. 2. Define a role wi ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

The ajax success function is not recognizing the if statement

Looking for help with HTML code <div class="vote"> <div data-post-id="@item.PostId" data-vote-rank="1" class="vote-arrow vote-up glyphicon glyphicon-chevron-up"></div> <div class="total-vote">0</div> <div data- ...

Animated CSS Checkmark Design

How can I create an animated Check-mark using CSS with SVG animation? I attempted the following code but it doesn't seem to be working. Any suggestions? DEMO: https://jsfiddle.net/b7Ln0jns/ CSS: @import "bourbon"; $color--green: #7ac142; $curve: c ...

Scrolling to a specific anchor in a React webpage when the URL is opened in

Imagine having a component "Post" that contains multiple components "Comment". How can we make the application automatically scroll down to a specific comment when entering a URL like this: /post/:postId/#commentId The route for postId /post/:postId is a ...

Transform post-back into PHP using JSON for Ajax posting

Currently, I am facing a challenge in integrating a Codeigniter application into Wordpress using a plugin. The trouble arises when the control encounters an issue while confirming the data for a new appointment. VIEW <div id="wizard-frame- ...

The React Modal component seems to be malfunctioning within the context of Nextjs

Out of the blue, this issue popped up and I'm puzzled about why it's happening. I have two modals (with different names) that are identical in structure but only one is functioning properly. Both modals use the React-Modal library. The first moda ...

Dividing Faces with Lengthy Edges in three.js into Two Separate Faces

I am currently working on a script that involves splitting overly long edges of faces into two separate faces instead of one large face. The final result is exported to a .obj file. Although the geometry reduction works fine, I have noticed some issues a ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...