Searching for a specific value within a hash in MongoDB

I am working with MongoDB documents formatted like this:

    {
      "_id": ObjectId("5406e4c49b324869198b456a"),
      "phones": {
        "12035508684": 1,
        "13399874497": 0,
        "15148399728": 1,
        "18721839971": 1,
        "98311321109": -1,
      }
    }

The phones field consists of a hash of phone numbers and their frequency of use.

I am trying to select all documents that have at least one phone number with a frequency of zero or less.

I attempted the following query:

    db.my_collection.find({"phones": { $lte: 0} })

Unfortunately, this query did not return the desired results.

Thank you in advance for any advice you can provide.

Answer №1

In MongoDB, performing a query like the one you are trying to do may not be straightforward. It is considered an "anti-pattern" to specify part of your data as "keys" in MongoDB. A better approach would be to model your data in a way where the "data" is a value to a key, instead of the other way around:

    {
      "_id": ObjectId("5406e4c49b324869198b456a"),
      "phones": [
        { "number": "12035508684", "value": 1 },
        { "number": "13399874497", "value": 0 },
        { "number": "15148399728", "value": 1 },
        { "number": "18721839971", "value": 1 },
        { "number": "98311321109", "value": -1 },
      }
    }

With this model, your query becomes simpler:

db.collection.find({ "phones.value": { "$lte": 0 } })

Trying to traverse the "keys" of an object/hash in MongoDB natively is not supported. You would need to use JavaScript evaluation for this, which can impact performance. An alternative would be using a $where query, like this:

db.collection.find(function() { 
    var phones = this.phones; 
    return Object.keys(phones).some(function(phone) { 
        return phones[phone] <= 0;
    }) 
})

It is recommended to reconsider the way you model your data in MongoDB and leverage the native operators for better query performance. Most queries in MongoDB require an explicit path to access any "key" inside an object/hash.

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

The method of pausing a function until the result of another function is returned

There is a function named 'updateProfile()' that includes a condition, which checks for the value of variable 'emailChangeConfirm' obtained from another function called 'updateEmailAllProcessing()'. The issue lies in the fact ...

Error alert: Index not defined!

I have a dropdown select that needs to be populated with values from a database. I then need to validate the selected value using a JavaScript function, which is already implemented. The dropdown list has two columns: one for ID identifiers and another fo ...

res.cookie function is unable to set cookies in the Chrome web browser

During development, I have a basic login page running locally on my machine (http://127.0.0.1:5500/index.html) and a simple express server running at http://localhost:3003 Despite seeing the server sending my access_token in response headers, Chrome brows ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

How can I translate these JQuery functions into vanilla JavaScript?

I am currently in the process of building a configurator using transparent images. The image configurator functions through a basic JQuery function: I have assigned each input element a data attribute called data-Image. This function identifies the data-Im ...

Find the identification number by searching through the text

I'm trying to find a way to retrieve the node id during a text search. Here's an example: http://jsfiddle.net/53cvtbv9/529/ I attempted using two methods to get the id of a node after the search: console.log($('#jstree').jstree(true). ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

At what point is the ajax call considered fully executed?

Whenever a client makes an AJAX call, they upload data to the server (HTTP request) and then receive data from the server (HTTP Response). Once the clients have received all the data, the AJAX request is considered successful, and the success callback func ...

Display multiple selection using JavaScript based on the element ID

I have a task to display the selected id using JavaScript, but currently, only the first select id is shown. Here is my HTML and JavaScript code: <tr> <td> <select name="jens_id[]" id="jens_id" required="" > <option ></op ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

Setting a completion flag using a factory in AngularJS

I'm struggling to create a factory that can set a completion flag for a value within an object. The object in question looks like this: {"key1":"value1", "key2":"value2", "key3":"value3"} My goal is to retrieve and operate on the value associated wi ...

Steps for placing a second pie chart alongside the initial one within a Bootstrap card

Is it possible to have two pie charts with different values using chart.js? I attempted to duplicate the script for the first chart to create a second one, but it did not display correctly. Why is the second pie chart not showing up? $(document).ready(fu ...

A guide to setting up pagination with mongoose and EJS while maintaining the search query during paging

Looking for help with Nodejs, EJS, Mongoose, and MongoDB. My issue is with implementing paging buttons in a table created from DB documents without losing the search query. Here is the flow of my application: Click on the search link to open the search ...

Issues with fundamental JavaScript client-side code

As a newcomer to the world of javascript and jQuery, I am diving into my first experiment with javascript. My initial focus has been on changing questions by clicking next or previous buttons. The goal is to create a dynamic quiz webpage that updates quest ...

Struggling with this mixed content problem

Encountering a problem while loading a js file: https://code.jquery.com/jquery-1.11.1.min.js, which is being loaded on my webpage in this manner: <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> Upon loading my webpage, an ...

Encountering an 'Error: Page Not Found' message on the live Heroku website

I have a MERN stack application in progress. The Node server is running locally and connected to the MongoDB Database. It is also set up to build and deploy on Heroku. However, when I click on "Open App" on the Heroku page, it displays "Cannot GET /". I m ...

Update content without reloading the page

I've implemented a function to delete an image in my action.js file: export const removeImage = (id, image_id) => async () => { try { const response = await axios.delete( `localhost:3000//api/v1/posts/${id}/delete/${image_id}`, ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...

Error: Knockout sortable array failing to render nested elements accurately

As a newcomer to Knockout.js, I have recently delved into the world of JQuery and the knockout-sortable project. My current project involves utilizing a complex data structure to present forms. Specifically, I am attempting to create a nested sortable arra ...

Unable to render dynamic ID in Next.js version 13.4.6 due to an issue

https://i.sstatic.net/x8oF1.pnghttps://i.sstatic.net/OEIL5.png Currently diving into next-js! Previously, I utilized dynamic id rendering in my projects. However, encountering errors now with the current version (next js 13.4.6). Having trouble identifyin ...