Is there a way to monitor changes in the alphabetical order of a field in mongodb?

Imagine I have a file in my mongo database with various documents stored in the CARS collection.

If I want to sort them, I can use:

db.cars.find().sort({car:1, price:-1})

Now, I am looking for a query that will return the top car of each category based on 'car'. Specifically, I would like to add a new field called "price_high" to these selections using

{$set:{"price_high"},{multi:true}}
.

'car':Chevy, 'price':100 //This is the top one from Chevy
'car':Chevy, 'price': 80 
'car':Chevy, 'price': 60 
'car':Lexus, 'price':99 //Top Lexus
'car':Lexus, 'price':90 
'car':Lexus, 'price':85 
'car':Maserati, 'price':99 //Top Maserati
'car':Maserati, 'price':96 
'car':Maserati, 'price':93 

This query should be executed only in the MONGO TERMINAL, not written into a file!

Answer №1

If you're delving into MongoDB for the first time, what you need to familiarize yourself with is the .aggregate() method. This function in MongoDB serves a similar purpose to "GROUP BY" in SQL and allows for various data manipulation operations.

To retrieve results and make updates to the data, you can use a process similar to this (preferably in bulk):

var bulk = db.collection.initializeOrderedBulkOp(),
    count = 0;

db.collection.aggregate([
    // Arrange data as needed
    { "$sort": { "car": 1, "price": -1 } },

    // Group by the initial entries for each car
    { "$group": {
        "_id": "$car",
        "doc_id": { "$first": "$_id" },
        "price": { "$first": "$price" }
    }}
]).forEach(function(doc) {
    bulk.find({ "_id": doc.doc_id }).updateOne({
        "$set": { "price_high": true }
    });
    count++;

    // Clear every 1000 processed and restart
    if ( count % 1000 == 0 ) {
       bulk.execute();
       bulk = db.collection.initializeOrderedBulkOp();
    }
});

// Process any remaining records
if ( count % 1000 != 0 )
    bulk.execute();

In cases where you have a small set of real samples, it may be more efficient to extract the necessary _id values and utilize $in with {multi:true} in your update query.

The core concept here is to employ .aggregate() to fetch the top documents (utilizing $first after $sort is crucial) and then execute the necessary actions to update the obtained results.

Answer №2

If you want to retrieve the highest prices for each car from a collection using the group aggregate function:

db.cars.aggregate(
[
{$group:
  {
  "_id": "$car",
  "price":{"$max":"$price"},
  "gid":{"$first":"$_id"}
  }
 }
 ]
  ).forEach(function(doc)
   {
   db.cars.update({"_id":doc.gid,"car":doc._id,"price":doc.price},
   {"$set":{"price_high" : true}});
 }

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

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

Differences between jQuery and Google Closure in terms of handling AJAX

Recently, I've been exploring the Google Closure Library for handling ajax calls. I came across an example that piqued my interest: goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // perform a cool action } els ...

Angular implementation of a reactive form including a child component

Upon inspection, I noticed that my father form component is displaying the values of nickName and name, but not the value of age. It seems that {{myFormFather.status}} does not recognize the component child. It's almost as if my child component is inv ...

Ways to resolve the issue of the experimental syntax 'jsx' not being enabled

I encountered an issue while trying to implement react-fancybox and received an error. https://i.sstatic.net/vgFha.png To resolve the error, I executed the following commands: npm install --save-dev @babel/preset-react, npm install --save-dev @babel/plugi ...

Get the refreshed values of JSON data

Recently, I've started using Java to fetch data from the web and found myself facing an issue. I am parsing JSON data from a specific website (Flightradar24.com) and saving it into a CSV file. However, as the values in the JSON are regularly updated, ...

The JSON query is successful in returning data, but as soon as I attempt to

In my extensive table (code_table), there are various types of records with different values. Some of these records include a json field, while others do not. To retrieve the records with json fields, I use the following query: select code_data from code_t ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...

What methods can be used to develop a data input code that avoids endless repetition?

For some reason, the name and score stored in varchar format in MySQL are arranged in descending order by score using a linked list. However, this leads to an endless loop when attempting to save the information. `public class PlayerController : MonoBehavi ...

What is the method for altering the value of a variable within a function?

Is there a way to update the value of a variable? I attempted the method below, but unfortunately, it was unsuccessful: function UpdateData() { var newValue = 0; $.ajax({ url: "/api/updates", type: &quo ...

Remove attributes from a collection of objects

Here is an array of objects: let array = [{ firstName: "John", lastName : "Doe", id:5566, weight: 70 },{ firstName: "Francis", lastName : "Max", id:5567, weight: 85 }]; I am looking to remove the properties "lastName" and "weight" for all obj ...

Is there a way to leverage the "locals" parameter in the jade compile() function on the client-side?

My Objective The server is a Node.js application. My goal is to share code with the client using Jade template helpers (for functions) or globals (for objects/variables). Any new helpers and globals should be accessible in every client template. This quer ...

Executing numerous xhttp.send requests within a single webpage

Hey there, I'm facing an issue with xhttp.send(); as it keeps giving me the error message net::ERR_EMPTY_RESPONSE Here is a snippet of my code. Whenever a user clicks too quickly, they get kicked off the page. Is there a way to prevent this? docum ...

Tips for executing nodemon and forever in the background

Good morning! Having an issue with my node.js server running in the background. I came across this helpful thread on Stack Overflow which suggested using Forever + Nodemon together I like the concept, however, when I implement it as shown here: forever ...

What is the best way to utilize a single Google Map component instance across multiple children?

Seeking a method to maintain the same Google Map instance throughout my entire app, as each map load incurs charges... Currently utilizing google-map-react. An instance of a new Map is created in ComponentDidMount, suggesting that it's important to k ...

Error in Node.js: [Error: Query parameter should not be empty]

I've been recently focusing on a project that involves sending the required name to my profile.js file using a POST request. However, whenever I try to access console.log(req.body.bookName) (as the data being sent is named bookName), it shows an error ...

Determine Specific Figures in a Listed Set

I am currently seeking a way to extract specific numbers from a list in order to perform calculations, but I'm uncertain about where to begin. For instance, if we start with an empty list such as list = [], and then later on call the list when users i ...

Tips for verifying the status and triggering a function with a delay in a React component

I have a scenario where I want to execute a function only if the state remains unchanged after being updated by a database fetch. Here's what I currently have: const [value, setValue] = useState(false) const func = () => { ... } setTimeout(()=&g ...

Guide on updating specific sections of text within a MariaDB database column

I'm looking to update a specific portion of text in a MariaDB 10.5 database table with a new value. For example: Database: users Table: humans Column: area Values: as shown below row 1: ["area1","area2","area 3",& ...

Passing Information to VueJs Modal Component

I am trying to send data from the first component to a modal in another component. Both components are located in the same place. I need to display the data from the first component in my edit modal form. Below is the code snippet: form.vue: <templat ...

Creating a private variable in Javascript is possible by using getter and setter functions to manage access to the

Is this the correct way to simulate a private variable? var C = function(a) { var _private = a + 1; // more code... Object.defineProperties(this, { 'privateProp': { get: function() { return _privat ...