Querying with complex aggregations in MongoDB for sorting operations

Can anyone help me with sorting a list of accommodations based on price and number of amenities they offer? The main challenges are converting the price (which is in string format starting with $) to an integer for proper sorting, and determining the count of attributes for each amenity.

This JSON structure provides relevant information about the accommodations. It includes details such as pricing, address, amenities, and reviews for each lodging option.

I attempted to use the MongoDB aggregate function to achieve this, but my limited experience with MongoDB is posing challenges. Here's a snippet of what I tried:

db.lodging.aggregate(
[
{$project: {"substring": {$substr: ["lodging.price", 1,-1 ]}} }, // Convert price from string to substring.
{$project: {intfield: {$toInt: substring}}}, // Convert substring to integer for sorting.
{$project: {}} // TO-DO: Calculate the number of amenities.
{$sort: {intfield: -1, numamenities: -1}}
]
);

Answer №1

Here is an effective aggregation method:

db.lodging.aggregate([
  {
    $addFields: {
      "intfield": {
        $toInt: {
          $substr: ["$lodging.price", 1, -1]
        }
      },
      "numamenities": {
        $size: {
          $objectToArray: "$lodging.amenities"
        }
      }
    }
  },
  {
    $sort: {
      intfield: -1,
      numamenities: -1
    }
  }
])

To start off the process, I used $addFields. Instead of $project, I opted for $addFields because it allows all fields in the document to be passed onto the next stage. If you had used $project with

{$project: {"substring": {$substr: ["lodging.price", 1,-1 ]}} }
, only substring would have been available in the following stage. Hence, $addFields was a better choice.

When dealing with intfield, note that I specified $lodging.price with a $ before lodging. This signifies to MongoDB that the value required is from the field lodging.price and not just the text "lodging.price".

For numamenities, I utilized $objectToArray to transform the lodging.amenities into an array, enabling the use of $size to determine the number of elements.

With intfield and numamenities now included in each document, the final step is to apply $sort.

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

Creating Customizable Badges That Can Be Embedded in Laravel

I am looking to implement organic promotion in my application using Laravel by providing badges, which are snippets of content that users can embed on their own websites when a URL is stored in our database. These badges could be similar to the DMCA embed ...

How can I change a PHP for loop to Javascript?

Can the following code be converted to JavaScript? for (let lift of liftDetails) { document.write('<option>'+ lift["LiftMakes"] +'</option>'); } ...

Documentation guide: best practices for indicating optional return values

I am tasked with properly documenting a function using JSDoc. The function triggers something if it returns true, otherwise it does not. However, the return value must always be of boolean type. Here is my proposed JSDoc documentation: * @return {boolean ...

The model's function received the error message "Not a valid function."

My project involves NodeJS, Express, and Sequelize(mysql2)... I am encountering an issue where I keep receiving the error message "is not a function". I have created a model and defined a function in the model as shown below: module.exports = (sequelize, D ...

What is the best approach to create a form wizard with validation using Vue.js?

I recently completed a Vue.Js project where I created a wizard based on a video tutorial. However, I am facing issues with form validation using the 'is-valid' and 'is-invalid' CSS classes that I have defined. Here is my code: <div c ...

The promise from mongoDB is resolved prematurely

Recently, I decided to incorporate Promises into my Node.js application. Currently, I am tackling the task of verifying if a user and password exist, then using MongoDB to search for them. However, I encountered an issue where the promise is being resolved ...

How does ES6 `import` syntax go about evaluating a module precisely?

Consider a scenario where we are dealing with four modules: A, B,C, and D Module A contains the following code: console.log("A evaluated") function AClass { console.log("A constructor") } var aObj = new AClass() export default aObj; In module B: impo ...

Using jQuery for newly added data does not yield the desired results

<ul id="myul"> <li id="myli1"></li> <li id="myli2"></li> <li id="myli3"></li> . . . . <li id="myli15"></li> </ul> In my code, I have a list with unique IDs for each item. I also have implemented ...

How can I add page transitions to my simple HTML website?

Working on an internal website project for my office using vue.js has been a rewarding experience. I appreciate how easily it allows me to manage multiple pages with dynamic content and seamless transitions. Unfortunately, my IT department is hesitating to ...

Is it a guarantee that a function called in the head section of a JavaScript for-of loop will only be executed once?

In both Firefox and Chrome, I tested the code snippet below: function test() { console.log("***") return [1,2,3] } for (const t of test()) { console.log(t) } After running this code, I noticed that the test function was only called once. T ...

How can nested fields be utilized to establish a many-to-many relationship in MongoDB/Mongoose?

Working on understanding how to establish a many-to-many relationship in mongodb/mongoose. I have created two Schemas: // User Schema var UserSchema = mongoose.Schema({ email: { type: String, index:true }, name: { type ...

Leveraging MongoDB's aggregation framework to tally occurrences of words in string matches

After analyzing the MATCHES ($match) provided for an aggregation: [ "palabra": "Hello", "palabra": "My name is Rafael" ] The following pipeline used for aggregate results in a total $sum of 2: var pipeline = [ { $match: { ...

There was an unexpected token syntax error while trying to assign the database URL from the environment variable "REACT_APP

I am facing an issue with setting an environment variable in my mongo.js file. Here is the code snippet where I have set the ENV variable: const mongo = require('mongodb').MongoClient; const assert = require('assert'); const ObjectId = ...

When passing req.body to another file for processing, it is displaying as undefined in node.js

Currently tackling an issue with a project involving nodejs where the request body is showing up as undefined Fetching some data on the client side, but encountering difficulties Received an error pointing out that the property is either undefined or nul ...

Creating Hbbtv applications with the help of a Firefox Addon

My curiosity lies in creating hbbtv apps and I am eager to learn how to run and test a complete hbbtv application package, specifically a videoplayer with multiple html pages, utilizing the FireHBBTV plugin on Firefox. Despite my extensive search efforts ...

Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap. During this process, I have encountered three peculiar issues. While I am confident that my jQuery code is properly functi ...

What is the best way to bring a function into another function from a separate file?

I am attempting to call the "changenavitemstate" function from the "Navbarlink" file. When I try to import the function into the file, I encounter an error. I have tried using props to access the function but have been unsuccessful. ...

Leveraging jQuery to implement onclick functionality within a Jinja2 loop

I'm currently working with Python, Flask, and Jinja2. When using a for loop, I want to be able to click on the {{ place.place_photo }} element to toggle its details. Initially, I had it functioning correctly but ran into an issue where clicking on on ...

Why aren't the correct error messages being shown when requesting from the network?

Struggling to figure out how to display informative error messages on the client side instead of generic ones? For instance, when attempting to register with an email that is already taken, users should see a message saying "<a href="/cdn-cgi/l/email-pr ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...