Retrieve data from a MongoDB collection based on a specific index field

I am looking to extract only the "thetext" field from a specific index in my database when the value of "comment_count" is 1.

This is the query I have tried:

db.getCollection('mongotesi').find({},{'bug.long_desc.1.thetext':'1'})

In addition to that, I want to display all the "thetext" fields. Here's the JSON structure for reference:

    { 
    "_id" : ObjectId("5613c8acc8e53ab811000083"), 
    "@attributes" : {
        "version" : "4.4.10", 
        "urlbase" : "https://bugs.documentfoundation.org/", 
        "maintainer" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f27203c3b222e3c3b2a3d0f2b202c3a222a213b29203a212b2e3b26202161203d28">[email protected]</a>"
    }, 
    "bug" : {
        "bug_id" : "31585", 
        "creation_ts" : "2010-11-12 08:55:00 +0000", 
        "long_desc" : [
            {
                "@attributes" : {
                    "isprivate" : "0"
                }, 
                "commentid" : "194230", 
                "comment_count" : "0", 
                "attachid" : "40242", 
                "who" : "eric.moret", 
                "bug_when" : "2010-11-12 08:55:52 +0000", 
                "thetext" : "Created attachment 40242ooo base fileI am running ooo 3.2.1 OOO320m18 (Build:9502). I am using an odb bas file to perform a mail merge on an odt file under writer. In the mail merge Wizard, on hitting Next in step 6. (Edit Document), the Status window - creating document opens up and generates my mailing. The crash happens reliably while performing this task. I have 118 items to generate.My error report id is: rpmrd6nAttached are the 2 files used for this merge."
            }, 
            {
                "@attributes" : {
                    "isprivate" : "0"
                }, 
                "commentid" : "194232", 
                "comment_count" : "1", 
                "attachid" : "40243", 
                "who" : "eric.moret", 
                "bug_when" : "2010-11-12 08:56:29 +0000", 
                "thetext" : "Created attachment 40243ooo write file"
            },    
        ], 
    }
}

Answer №1

Arrays can be specified as [ skip , limit ], where the first value indicates how many items in the array should be skipped and the second value denotes the number of items to retrieve.

To find the first object in an array, you can use the $slice query method.

db.collection.find({},{"bug.long_desc":{"$slice":[0,1]},"@attributes":0})

If you want to exclude the first object and retrieve the second one, you should modify the query like this:

db.collection.find({},{"bug.long_desc":{"$slice":[1,2]},"@attributes":0})

EDIT

If you need to print out the exact matching text, you can use the forEach function along with the $slice method:

db.collection.find({},{"bug.long_desc":{"$slice":[0,1]},"@attributes":0}).forEach(function(doc){print(doc.bug.long_desc[0].thetext);})

Answer №2

MongoDB doesn't offer this functionality, but there's a solution that can accomplish the same thing:

const treeMath = require('tree-math');
const longDescArray = db.getCollection('mongotesi').find({},{'bug.long_desc':'1'});
const bugText = {};

treeMath.find(longDescArray, (path, val) => {
   if(path[3] === 'thetext') {
      treeMath.setPath(bugText, path, val);
   }
});

console.log(JSON.stringify(bugText, null, 2));

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

Hiccup: encountering ENOTFOUND in nodejs when making a get request

Running a web server on node, here is the code: var restify = require('restify'); var server = restify.createServer(); var quotes = [ { author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm p ...

The class `MappedListIterable<dynamic, dynamic>` cannot be assigned to the type `List<Weather>`

I have created three classes to handle JSON parsing from an API call. Here are the classes: class CurrentWeatherInfo { double temperature; double feelsLike; double minTemperature; double maxTemperature; int pressure; int humidity; CurrentWea ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

Obtaining a distinct movie identification (tmdb API) utilizing '@PathParam'

I recently started working on my first spring boot project, but I feel like I still have a lot to learn. Despite searching on Stack Overflow and Googling for answers, I haven't found a solution yet. It would be greatly appreciated if someone could pr ...

What is the level of support JACKSON offers for Java Generics?

Currently, I am engaged in a project that utilizes the restFul approach and is schema based. In this project, we are utilizing JAXB for XSD to JAVA conversion. Below is the structure of a class used in this project: @XmlAccessorType(XmlAccessType.FIEL ...

Is there a way to retrieve attribute values from a JSON object using JMESPath?

I am searching for the value of the _ISSUE_CURRENCY variable. The JSON data I have is as follows: { '#value': 'VR-GROUP PLC', '_ISSUE_CURRENCY': 'EUR', '_PRICING_MULTIPLIER': 1, '_TYPE ...

Arrange the complex nested array or final JSON based on the key's name

I am currently in the process of sorting a rather large multidimensional array based on key names (and not values), while also aiming for the fastest possible solution. The resulting array will be converted to JSON and stored in a file, so if there is a m ...

Issue with posting data to a JSON file using Vue and axios

I am encountering an issue with axis posting to a local .json file. The error I am receiving is: POST http://localhost:8080/todolist.json 404 (Not Found) TodoListEditor.vue?b9d6:110 Error: Request failed with status code 404 at createError (createErr ...

Suggestions for updating the 'begin' and 'finish' variables transmitted through ajax on fullcalendar?

Shown below is the URL to request JSON data via Ajax: '/php/get-events.php?start=2015-05-31&end=2015-06-07&_=1433154089490'. This query will fetch JSON data from 2015-05-31 to 2015-06-07. However, I am looking to retrieve data over a ...

A web service that retrieves data in the form of a JSON object and returns

I need assistance with creating a webservice in .NET Framework 4.0 that will generate and return data in json format. Here is the code I have for the WebMethod: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetLobMonth(st ...

Reading various JSON files in Objective C

In short, I need to access only the parent element in the JSON file. How to parse multiple JSON in Objective-C?) I am trying to extract the author > NAME from this JSON. The code for this task is as follows: NSURL *blogURL = [NSURL URLWithString:@"*remov ...

Removing Embedded Json Element from a Collection in AngularJS HTML

In my JSON Collection, I want to display the Email ID that is marked as IsPreffered = TRUE using AngularJS HTML without using JavaScript. This is my JSON Collection: { "user" : [ { "Name" : "B. Balamanigandan", "Email": [ ...

Extracting an array of integers from JSON using SQL Server 2016

Upon receiving a valid JSON string from the client side, which contains an array of integer values: declare @JSON nvarchar(max) = N'{"Comments": "test", "Markets": [3, 151]}' The question arises on how to accurately select the market IDs. When ...

Serilog does not automatically interpret file name templates

My current configuration for using Serilog is as follows: { "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": "Debug", "Enri ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

When querying data in Express.js and Node.js with Mongoose, the results may not match the expected outcome

One issue that occasionally arises is displaying the wrong user on the screen (someone accessing another person's session). This occurrence seems to be rare and possibly only happens during concurrent actions. If you notice anything in this code that ...

Verify if there are any new updates to a JSON file on the web and then analyze it against a file that is

Currently, I am exploring the depths of a dense forest: I possess a universal app with navigation capabilities that showcases data stored in a plist file. For my next update, I aim to transition the database to a JSON file hosted on my server. The app will ...

Issue with jQuery Ajax not functioning properly across domains in Internet Explorer 9

I am facing an issue accessing a REST web service through jQuery. The Access-Control-Allow-Origin is correctly set to * as seen in Firebug, and Chrome/Firefox have no trouble accessing it. However, Internet Explorer seems to be causing trouble. I have gon ...

Leveraging AJAX for fetching data from a deeply nested JSON structure

My AJAX request is functioning properly: $.ajax ({ url: 'api.php', type: 'GET', data: {search_term: data}, dataType: 'JSON', success: function(data) { $('#div').html('<p>Consti ...

Bower consistently installs the most up-to-date version instead of the version that was explicitly specified

Despite the version specified in the "bower.json" file, bower (v1.8.0) doesn't adhere to it and instead downloads the most recent version of the library available. It seems like it's not taking the version into account at all. Even downgrading to ...