Discover the longest data length within the key values of the collection

{
  "_id" : ObjectId("59786a62a96166007d7e364dsadasfafsdfsdgdfgfd"),
  "someotherdata" : {
    "place1" : "lwekjfrhweriufesdfwergfwr",
    "place2" : "sgfertgryrctshyctrhysdthc ",
    "place3" : "sdfsdgfrdgfvk",
    "place4" : "asdfkjaseeeeeeeeeeeeeeeeefjnhwklegvds."
  }
}

I have a vast array of similar records in my collection. My task is to sift through all the someotherdata entries and perform the following actions:

  1. Verify if specific fields are present (for example, place1 might be available in certain records while place4 may not)
  2. Determine the longest string record among them

The desired output should display the character count for the lengthiest entry as shown below:

{   
  place1: 123,
  place2: 12,
  place3: 17
  place4: 445
}

Given that I am utilizing Mongodb version 3.2.9, which lacks the latest aggregate functions, my approach involves leveraging the Mongodb shell.

EDIT: To clarify further, the goal is to identify the longest record across all documents in the collection. Even though there could be thousands of documents, the result should showcase the longest string length for each field throughout the entire collection.

Answer №1

To reduce down to the largest values for each key, you can use the .mapReduce() method:

db.collection.mapReduce(
  function() {
    emit(null,
      Object.keys(this.someotherdata).map(k => ({ [k]: this.someotherdata[k].length }))
       .reduce((acc,curr) => Object.assign(acc,curr),{})
    );
  },
  function(key,values) {
    var result = {};
    values.forEach(value => {
      Object.keys(value).forEach(k => {
        if (!result.hasOwnProperty(k))
          result[k] = 0;
        if ( value[k] > result[k] )
          result[k] = value[k];
      });
    });
    return result;
  },
  { 
    "out": { "inline": 1 },
    "query": { "someotherdata": { "$exists": true } }
  }
)

This process emits the "length" of each key in the sub-document path for every document. In the reduction phase, only the largest "length" for each key is returned.

In mapReduce, maintaining the same structure in both emit and reduce functions is important. It helps with handling a large number of documents by reducing them in gradual batches.

The output for the sample document provided in the question will be like this. The results represent the maximum values across all the documents in the collection, especially when dealing with more entries:

   {
        "_id" : null,
        "value" : {
            "place1" : 25.0,
            "place2" : 26.0,
            "place3" : 13.0,
            "place4" : 38.0
        }
    }

If using MongoDB 3.4 or later versions, you can achieve the same outcome using the .aggregate() method:

db.collection.aggregate([
  { "$match": { "someotherdata": { "$exists": true } } },
  { "$project": {
    "_id": 0,
    "someotherdata": {
      "$map": { 
        "input": { "$objectToArray": "$someotherdata" },
        "as": "s",
        "in": { "k": "$$s.k", "v": { "$strLenCP": "$$s.v" } }
      }
    }
  }},
  { "$unwind": "$someotherdata" },
  { "$group": {
     "_id": "$someotherdata.k",
     "v": { "$max": "$someotherdata.v" }    
  }},
  { "$sort": { "_id": 1 } },
  { "$group": {
    "_id": null,
    "data": {
      "$push": { "k": "$_id", "v": "$v" }
    }    
  }},
  { "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": "$data"   
    } 
  }}
])

This code snippet produces similar results:

{
    "place1" : 25,
    "place2" : 26,
    "place3" : 13,
    "place4" : 38
}

Answer №2

Utilize cursor.forEach to cycle through the dataset. Maintain a record of the highest numerical values (initially set at -1, then updated when a higher value is discovered). Display these values using either print() or printjson()

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

Using a background image in a React component

Currently, I am working on a webpage and facing an issue while trying to set a background image for a Material UI element using the background-image CSS property. Despite researching online for solutions, I am unable to make the image appear. P.S.1: I eve ...

Navigating to new location following the final iteration in a loop of asynchronous updates in MongoDB

Currently, I am developing an application using Node/Express/Mongodb/Mongoskin. I am facing an issue with the code responsible for updating a collection of documents: db.collection('invoices').find().toArray(function(err, dbDocs) { if (err) t ...

Issues presenting themselves with Material UI Icons

I need some help with a problem I'm having. I'm trying to integrate my React app into an Angular app, and everything is working fine except for the material-ui/icons. They appear, but they are not displaying correctly! I have made sure to use th ...

Is there a way to remove a row when fetching data in ReactJS?

In this section, I am retrieving data from an API to populate a table. renderItem(data, index) { return <tr key={index} > <td> {data.Employee_ID} </td> <td>{data.Employee_Name}</td> <td& ...

Edit an unspecified property within a Mongoose schema and then proceed to save the changes

I've created a user schema as shown below var UserSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true }, location: String, picture: String, i ...

Aggregation in Mongodb - the power of processing data efficiently

{ "items": [ { "id": "5bb619e49593e5d3cbaa0b52", "name": "Flowers", "weight": "1.5" }, { "id": "5bb619e4ebdccb9218aa9dcb", "name": "Chair", "weight": "8.4" }, { "id": "5bb619e4911 ...

using localStorage to store multiple keys

My code attempts to generate multiple keys (user_0,user_1,user_3...) for the record(username,password,email). Even though I'm getting an alert saying "The data was saved," nothing is actually being stored in the local storage. Can someone help me figu ...

Vue's animation happens without any delay or duration

I followed the Vue animation instructions from the documentation carefully: The transition component has a name="fade" attribute. v-if is placed in the child of the transition element. The styles were directly copied from the documentation provi ...

Unable to establish a hyperlink to specific section of page using MUI 5 Drawer

When attempting to link to a specific part of my first page upon clicking the Shop button in the navigation Drawer, nothing happens: https://i.stack.imgur.com/FUQCp.png This snippet shows the code for the MUI 5 Drawer component: <Drawer anch ...

Execute a jQuery function every time the class of the parent container div changes

I am seeking to trigger the function below whenever its containing div parent <div class="section">...</div> transitions to an "active" state, for example: <div class="section active">...</div> $(".skills-grid__col").each(function ...

Mastering browser console manipulation using a script

I need help finding a way to automate a task on a website, such as clicking a button. I have a JavaScript code that can perform the task when run from the browser console. However, I want to find a way to pass this JavaScript code to the console without ...

What are the steps to fetch JSON data from a different domain server using AJAX?

I'm facing an issue with the API I'm using for my ajax call. It returns json and does not support jsonp, which unfortunately cannot be changed. Every time I try to use the code snippet below, I encounter a 'missing ; before statement' e ...

Using a global variable in Vue and noticing that it does not update computed variables?

Currently, I'm in the process of developing a web application and have begun implementing authentication using firebase. Successfully setting up the login interface, my next step is to propagate this data throughout the entire app. Not utilizing Vuex ...

Using Framework7 and AngularJS to efficiently load pages

When creating a phone application using phonegap, AngularJS, and Framework7, I encountered an issue with the page swapping functionality of Framework7. The problem arises because Framework7 injects new HTML pages into the DOM dynamically when a user click ...

Switching variables using jQuery tabs

I'm looking to enhance my Google-style instant search feature that is currently powered by a jQuery script fetching results from a PHP file. My goal is to enable users to change the search destination by clicking on a specific link. How can I modify t ...

Conflicting Angular components: Sorting tables and dragging/dropping table rows

In the current project I'm working on, I've integrated both angular table-sort and angular drag-drop. However, I ran into an issue where dragging a row and attempting to drop it onto another row causes the table sort to forcefully rearrange the r ...

Adjust the color of a selected edge in Three.js

let cubeEdges = new THREE.EdgesHelper(cube, 0xff0000); cubeEdges.material.linewidth = 5; scene.add(cubeEdges); A cube has been created using the following code: new THREE.Mesh(new THREE.BoxGeometry(200, 200, 200, 1, 1, 1, materials), new THREE.MeshFaceMa ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...

Encountering an issue with vue-mention where the error message states that "this.$scopedSlots.default is

// After running "npm why vue" <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3640435376041800180704">[email protected]</a> node_modules/vue dev vue@"^2.6.12" from the root project vue@"^2.5.17" from <a hr ...

Creating two separate canvas elements with their own unique JavaScript code can be achieved by first defining each

In my current project, I am utilizing the power of Three.js to craft a 3D cube that can both translate and rotate within a 3D space by harnessing data from accelerometer and gyroscope sensors. Initially, I managed to create one canvas that accurately disp ...