Searching in MongoDB: Retrieving a specified number of results with a specific field filter

Currently using MongoDB and in need of assistance with making a query. Specifically, I would like to perform a search on my user collection that includes a field named "country".

For example:

{
    "name" : "John",
    "country" : "FR"
}

For instance, I am interested in retrieving 30 users from France. If there are at least 30 French users in the database, then simply return those 30. However, if there are fewer than 30 (let's say 12) users from France, then I would like to retrieve all 12 French users along with an additional 18 users, regardless of their country of origin, to make up the total of 30.

I am curious whether this can be achieved through a standard query or if I need to resort to utilizing MapReduce.

Answer №1

In my opinion, accomplishing this task in a single query is not feasible.

  • Firstly, retrieve the count of documents with country: "FR".
  • If the count is 30 or more, proceed to fetch exactly 30 documents using the cursor.limit method. However, if the count is less than 30, retrieve all documents where country: 'FR' and then enhance the result by executing an additional query that retrieves documents where country is not equal to FR. This can be achieved using the .apply() function along with the .push method.

    var documentCount = db.collection.count({ "country": "FR" });
    var resultSet = [];
    
    if (documentCount >= 30) {
        resultSet = db.collection.find({ "country": "FR" }).limit(30).toArray();
    }
    
    if (documentCount < 30 ) { 
        resultSet = db.collection.find({ "country": "FR" }).toArray();
        resultSet.push.apply(resultSet, db.collection.find({ "country": { "$ne": "FR" }}).limit(30-documentCount).toArray());
    }
    

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

Controlling Material-UI using a custom .css stylesheet

Are there alternative methods for customizing Material-UI components using CSS stylesheets? I'm aware of the {makeStyles} method and JSS overrides, but I find it messy in the code and confusing when trying to modularize it in other files. Is there a ...

Could the abundance of JavaScript files in Angular 2 be hindering its performance?

Having experience with Angular 1.x, I am now delving into the world of Angular 2. As I begin, I am struck by the multitude of js scripts required to be added to our index.html file just to get started. Even when excluding angular's own js files and c ...

Tips for ensuring a watcher only runs once in each digest cycle, regardless of how many times the property is modified

I am facing an issue with my function $scope.render() that relies on the value of $scope.myProperty to render a chart. Whenever myProperty changes during a digest cycle, I need to ensure that $scope.render() is called only once at the end of the digest cyc ...

`Persisting a saga in Rebus with MongoDB: A step-by-step guide`

I'm currently in the process of setting up a bus, and I am looking to configure how Rebus will persist sagas. My plan is to use MongoDB with the Official C# Mongo Driver version 1.10 for saga persistence. This is what my configuration code looks like: ...

Unable to generate StumbleUpon traffic for a URL through AJAX due to the API returning text/plain

I'm attempting to acquire StumbleUpon views for a specific URL using $.ajax. This is the API I am utilizing: http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://example.com/ Here is the complete code snippet: $.ajax({ type: "GET ...

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

Issue with AngularJS ng-repeat and ng-show not functioning properly upon page reload

Hey there! I'm facing an issue with my web application that I built using AngularJS and Spring. This platform allows users to post messages, and I've written the following code in my Angular controller. <div class="row" ng-repeat="message in ...

"Curious about the outcome of the upsert operation using the Mongo node driver - was it an insertion

Currently working with the MongoDB native node driver. When performing an upsert like this: collection.update(query, setData, { upsert: true }, callback); Is there a method to determine whether the upsert resulted in an insert or an update? In the Mongo ...

how can I enable pass-through functionality in express middleware?

Currently, I have a POST API endpoint named /users which is used to retrieve the list of users. The reason behind using POST instead of GET is because the request body can be quite large and it may not fit in the URL for a GET request. In this scenario, i ...

What is the process for uploading an image with express-fileupload?

Looking to upload an image to Cloudinary via Postman using the express-fileupload library for handling multipart forms. Here is a snippet from my index.ts file: import fileUpload from "express-fileupload"; app.use(fileUpload()); In my controller ...

Anticipating the conclusion of a pending GET request

Currently, I am developing a system to create user accounts. There is a function in place that checks for the existence of a username and returns false if it doesn't exist. However, when another function calls this username checker, it automatically ...

JavaScript implementations of basic Prolog predicates

Are there any proven methods for defining simple prolog predicates and asserting facts in javascript client code? I came across which seems to rely on a server-side "toy" interpreter. ...

Encountering an issue with undefined property 'path' while attempting to upload an image on the frontend in React

I have encountered an issue while trying to upload an image on the frontend. The error message displayed is: message: "Cannot read property 'path' of undefined" status: "fail" When I log req.file on the backend and attempt to ...

I am unsure about how to properly implement the reduce function

I am struggling with implementing the reduce function in my code. I have data output from a map function that consists of two documents. For example, one document contains: key "_id":"AD" "values" { "numtweets" : 1, "hastags" : ...

PHP response is blank when password_hash or password_verify functions are used

My application utilizes JavaScript to retrieve a string and send it via POST to a PHP file on the server for processing. The PHP receiver is responsible for parsing the string, performing tasks, and sending back status updates to JavaScript. However, after ...

Occasional jquery issue causing font to render incorrectly within iframe

Currently facing a bug that needs resolution, the issue has been identified but unsure of the solution. An iFrame is loaded with content via jQuery like this: var content = {{ json_encode($template) }}; $('#preview-iframe').contents().find(&apo ...

Having trouble with CSS transitions in a Next.js or Tailwind application?

"use client"; import React, { useState } from "react"; import Image from "next/image"; import Link from "next/link"; const NavigationBar = () => ( <div id="navbar"> <Link href="/">Home</Link> <Link href="/about">About& ...

Utilizing MongoDB's aggregation framework for calculating moving averages

If you have a dataset containing documents with a date or period property (e.g. 2013-01), what is the most effective method for calculating moving average statistics (e.g. a 3-month average) utilizing MongoDB's aggregation framework? ...

Remove an item from a multidimensional array that contains a specific key-value pair

I need to remove the low-level object (for example, in the code below, under personal data there are two objects, I want to delete the one where action is "OLD") under each section where the "action" is "OLD" I'm utilizing lodash in my current projec ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...