What is the best way to fetch the most recent article from every category using mongodb?

I am currently working with the following article schema:

var articleSchema=new Schema({
    id : Number,
    title : String,
    sefriendly : String,
    created : Date,
    categories: [
        {
            id: Number,
            name: String,
            sefriendly: String,
            image: String
        }
    ],
    author: {
        id: Number,
        name: String
    }
});

I am looking to retrieve the latest article for each category from a set of categoryIds, sorted by the 'created' field. For example, if my categories include Cinema, TV, Music, and Books, I want to retrieve the latest article for each category. Is it possible to achieve this in a single query?

Answer №1

To begin, establish an index for both the created date and category IDs:

db.article.ensureIndex({"created":-1,"categories.id":1})

Next, retrieve the most recent article:

db.article.aggregate(    [  {$unwind : "$categories"}     { $sort: {"created":-1,"categories.id":1 } },      {        $group:          {            _id: {"categories_id":"$categories.id"},            lastDate: { $last: "$created" }          }      }  ] ,{"allowDiskUse":true})

There may be a small syntax error in the code

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 are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

Unique alphanumeric code following the inclusion of a JavaScript file

I'm encountering an issue with a webpage that incorporates two JavaScript files. When inspecting it using firebug, I noticed that every time the page loads, these two files are included with the prefix ?_=someRandomNumber I'm unsure about the or ...

Exploring the Possibilities of Utilizing the FindOne Mongoose Function in Combination with E

I am currently trying to implement the mongoose findOne method on my date model property in order to retrieve data from the most recent document. I am using the EJS templating system and encountered an error when attempting to use this method in my view: } ...

MongoDB: utilizing the $elemMatch operator

I've been experimenting with using the $elemMatch operator to search for a specific object within an array. I have uploaded the following dataset into a collection called trails: { "Copper" : [ {"name" : "Spaulding Bowl", "level" : "Extreme T ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Encountering issues with browser tabs and Socket.IO

I'm currently working on a real-time chat using Socket.IO, but I've encountered a major issue. The aim is to allow users to log in, select another connected user, and start chatting... var http = require('http'), fs = require(&ap ...

Next.js: Uh-oh! Looks like we've hit an obstacle with Error 413 Request Entity

I've encountered an issue while attempting to upload large files using Next.js. I've set up an onChange function for my file input, and here's the code snippet: const handleFileUpload = () => new Promise(async (resolve) => { if(ref ...

I need help figuring out how to get a horizontal scrollbar positioned at the top of a div to function properly once the content has been loaded using ajax

HTML CODE <div id="scrollidout" style="overflow: auto; overflow-y: hidden; "> <div id="scrollidin" style="padding-top: 1px; height: 20px; width: 1000px">&nbsp;</div> </div> <div class="resultcontent" style="overflow ...

Ensure that the jQuery Knob is set to submit any modifications only after the final adjustment

Utilizing jQuery Knob by anthonyterrien, I have configured the step to be 20. My goal is to transmit the knob's value to the server. The issue arises when the change function is triggered every time the user adjusts the knob using either a right or le ...

Sending data to various databases using a consolidated form in AngularJS, NodeJS, MongoDB, Mongoose, and ExpressJS

Is it possible to have a single form that can post data to two different collections in MongoDB? Here is an example of how the HTML code might look: <form> ...Field1 ...Field2 ...Field3 ...Field4 </form> And here is an example of ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

Issue with Pymongo: Unable to filter collection by epoch date

I am facing an issue with filtering a Mongodb collection based on a date field in the document stored in unix epoch format. myquery = {"created_at": {"$gt": 1623384000}} docs = mycollection.find(myquery) Expectedly, this should return ...

Steps for building JSX with a loop

Recently diving into the world of React and Javascript, I've been attempting to assemble a JSX 'tree' dynamically using a loop rather than hard-coding the data. However, I find myself facing a hurdle where Visual Studio Code insists on havi ...

How can I take a screenshot from the client side and save it on the server side using PHP?

Currently, I am exploring the possibility of screen capturing at the client side. It appears that the "imagegrabscreen()" function can only capture screens on the server side. After some research, I discovered a new function that allows for screen capture ...

Is there a missing X-AppEngine-Region in the headers of the AppEngine application?

I've been trying to access the Region and Country in my request, but it seems like the X-AppEngine-Region and X-AppEngine-Country headers are missing. Sometimes I see headers like alt-svc content-length content-type date etag server status via ...

Pinia: Is it better to invoke '{myStore}' or 'return myStore' within the return statement?

I'm currently working on integrating a Pinia store into a component of my Vue app and I'm puzzled by the need to return the store in { } instead of just returning it as is. Can someone clarify the distinction between return {foo} and return foo f ...

Using npm link with Webpack results in eslint errors

I have a multi-package project setup, where I have one JavaScript package that depends on a TypeScript library. Initially, I was using Sinopia and had to reinstall the TypeScript library every time I made changes to it. Then I discovered npm link and thoug ...

Enhancing the appearance of a Class Component with Material UI using useStyle

I am trying to style the Class Component using useStyle instead of hooks, but I am having trouble figuring out how. Here is my code snippet: import React,{Component} from 'react'; import Avatar from '@material-ui/core/Avatar'; import { ...

Filtering data based on the model in React Native allows you to refine and organize

This code snippet represents a modal that contains two custom dropdown components, a text input, and a button. When the button is clicked, it filters data from an API. Currently, I am struggling to create a functional filter function despite multiple atte ...

Ajax login feature not redirecting to login popup after successful login

When attempting to open a popup by clicking on the login window, a pop-up appears with a URL requesting username and password along with Google sign-in. However, when a user tries to log in using Google sign-in through the pop-up, it fails to redirect to ...