Querying MongoDB to retrieve particular elements from an array within a collection

Results collection contains the following data.

_id                 "9FK5k755ueAYdfip3"
    createdAt       Date {Sat Mar 12 2016 19:58:46 GMT+0100 (CET)}
    results         [Object { errorId="uX6byeiuGjRNXTj6s",  error="02/09/15 13:01:29  backu...ox file was not found. ",  time="02/09/15 13:01:29"}, 
                    Object { errorId="uX6byeiuGjRNXTj6s",  error="02/09/15 13:01:29  backu...ox file was not found. ",  time="02/09/15 13:01:29"},
                    Object { errorId="uX6byeiuGjRNXTj6s",  error="02/09/15 13:22:42  backu...ox file was not found. ",  time="02/09/15 13:22:42"}, 
                    432 more...]

    results:

    0   Object { errorId="uX6byeiuGjRNXTj6s",  error="02/09/15 13:01:29  backu...ox file was not found. ",  time="02/09/15 13:01:29"}  
    1   Object { errorId="uX6byeiuGjRNXTj6s",  error="02/09/15 13:01:29  backu...ox file was not found. ",  time="02/09/15 13:01:29"}   
    2   Object { errorId="uX6byeiuGjRNXTj6s",  error="02/09/15 13:22:42  backu...ox file was not found. ",  time="02/09/15 13:22:42"}

    ...

    14    Object { errorId="5vfLjdbaQLgbuCiNZ",  error="02/09/15 16:04:10  backu...minated with an error. ",  time="02/09/15 16:04:10"}   
    15    Object { errorId="5vfLjdbaQLgbuCiNZ",  error="02/09/15 16:04:10  backu...minated with an error. ",  time="02/09/15 16:04:10"}   
    16    Object { errorId="5vfLjdbaQLgbuCiNZ",  error="02/09/15 16:04:10  backu...minated with an error. ",  time="02/09/15 16:04:10"}

    ...

    183    Object { errorId="uX6byeiuGjRNXTj6s",  error="03/13/15 13:36:24  backu...ox file was not found. ",  time="03/13/15 13:36:24"}
    184    Object { errorId="uX6byeiuGjRNXTj6s",  error="03/13/15 13:42:39  backu...ox file was not found. ",  time="03/13/15 13:42:39"} 
    185    Object { errorId="uX6byeiuGjRNXTj6s",  error="03/13/15 13:42:40  backu...ox file was not found. ",  time="03/13/15 13:42:40"}

I am looking for a query that retrieves all documents with a specific errorId within the results arrays.

I have attempted various queries without success.

For example:

    Results.find ({ results: { $elemMatch : { errorId: 'uX6byeiuGjRNXTj6s'}}})
    Results.find ({ results: { $elemMatch : { Key: 'errorId', 'errorId': 'uX6byeiuGjRNXTj6s'}}}).fetch()
    Results.find ({'results.errorId.$' : 'uX6byeiuGjRNXTj6s'}).fetch()

Your assistance would be greatly appreciated.

Thank you!!!

Answer №1

Give it a shot by using the power of aggregation

Results.aggregate([{$unwind: '$results'},
                   {$match: {'results.errorId': 'uX6byeiuGjRNXTj6s'}}])

Answer №2

To achieve this, you can utilize the $elemMatch operator in MongoDB. While the Mongo documentation does offer some initial examples, in your specific scenario, it's recommended to use:

{ results: { $elemMatch: { errorId: "abc"} } }

If for any reason that doesn't yield the desired results, as indicated in the mongo documentation, an alternate query could be formulated as follows:

{ "results.errorId": "abc" }

Answer №3

When trying to execute queries from the browser console, I received varying results:

    Results.find({ results: { $elemMatch: { errorId: "uX6byeiuGjRNXTj6s"} } }).fetch()
    [Object { _id="9FK5k755ueAYdfip3",  results=[435],  createdAt=Date}]

    Results.find({ results: { $elemMatch: { "results.errorId": "uX6byeiuGjRNXTj6s"} } }).fetch()
    []

    Results.aggregate([{$unwind: '$results'},{$match: {'results.errorId': 'uX6byeiuGjRNXTj6s'}}]).fetch()
    TypeError: Results.aggregate is not a function


    ...gregate([{$unwind: '$results'},{$match: {'results.errorId': 'uX6byeiuGjRNXTj6s'}...

The first query returned all ids instead of just "uX6byeiuGjRNXTj6s". The other two queries did not work. I proceeded to run them directly (using meteor mongo) from the database and obtained the following outcomes.

     db.results.find({ results: { $elemMatch: { errorId: "uX6byeiuGjRNXTj6s"} })
      - returned ALL ids

     db.results.find({ results: { $elemMatch: { "results.errorId": "uX6byeiuGjRNXTj6s"} })
     - returned empty

     meteor:PRIMARY> db.results.aggregate([{$unwind: '$results'},{$match: {'results.errorId': 'uX6byeiuGjRNXTj6s'}}])
    { "_id" : "9FK5k755ueAYdfip3", "results" : { "errorId" : "uX6byeiuGjRNXTj6s", "error" : "02/09/15 13:01:29  backup.swatycomet.lan nsrd Error encountered while re-signing lockbox 'D:\\EMC\\Networker\\nsr\\lockbox\\backup\\clb.lb': The lockbox file was not found. ", "time" : "02/09/15 13:01:29" }, "createdAt" : ISODate("2016-03-12T18:58:46.967Z") }
    ...

The third query yielded the desired results. Subsequently, when attempting to execute that query in my Meteor code:

 console.log(Results.aggregate([{$unwind: '$results'},{$match: {'results.errorId': 'uX6byeiuGjRNXTj6s'}}]));

An error occurred instead of returning the results.

Error message during template helper execution: .errors@http://localhost:3000/app/client/templates/results/results.js?951539bd4f24742e5d7a64530c2463bfe41fde91:33:21 bindDataContext/<@http://localhost:3000/packages/blaze.js?9391df93ba5076c2cfc61ee68724eb79b65f00d9:2986:14

What could be the issue here?

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

JSON format is used for returning values from WebMethod calls

How can I retrieve values from a Webmethod and format them in JSON for the client? I have two static int values that need to be returned. Do I have to create a new object with these properties each time, or is there a more efficient way to handle this? Th ...

Performing sub-queries or joins with embedded/nested documents in MongoDB using C# LINQ

I am facing an issue similar to the example below, where I am encountering an exception that states - System.ArgumentException: Expression of type 'System.Collections.Generic.IEnumerable1 ' cannot be used for parameter of type 'System.Linq. ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

Switch between pages within a reactjs application by utilizing react router

Greetings! I am currently diving into the world of reactjs and experimenting with navigation from one page to another by simply clicking on a link through react router. In my home.js file, I have listed out some interesting places and I aim to click on one ...

Leveraging the `app.get()` method in Firebase cloud functions to retrieve and interact with files

I am currently integrating Firebase Hosting with Firebase Functions to restrict access to .html content only to users with a valid Firebase token. Within my iOS app, I can successfully send the token when accessing Firebase Hosting. The Cloud Function dec ...

presentation not visible at first

I'm facing an issue with adding a slideshow to the header of my website. When the page initially loads, the slides do not appear; instead, I see the dots and arrows positioned higher than they should be. However, when I click on a dot or the "next pag ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Webpack returns an undefined error when attempting to add a JavaScript library

I am a newcomer to webpack and I am attempting to incorporate skrollr.js into my webpack setup so that I can use it as needed. However, I am unsure of the correct approach for this. After some research, I have found that I can either use an alias or export ...

I am looking for a way to showcase buffer data as an image in a React application

Need help with displaying images in a react application? function App() { const [imageData, setImageData] = useState(); useEffect(() => { const fetchData = async () => { const response = await axios.get('http://localhost:8000' ...

The destroy method of Chart.js does not appear to have any impact on the

Hello, I've come across this issue in my react app that I need help with: this.chart = new Chart(node, options); // adding data to the chart ... this.chart.destroy(); this.chart = null; this.chart = new Chart(node, options); // adding data to the cha ...

What is the best method for incorporating headers and custom server-side .js in an express.js / node.js application?

Recently, I've been working on developing a data-driven HTML site specifically tailored for developers at our company. The main concept involves setting up a server using node.js v0.12+ / express v4+ to handle various functions for accessing a large d ...

Explaining the process of defining a function and addressing the situation of inserting "variable parameters/arguments" in case the first parameter/argument is deemed incorrect

I came across an interesting article called Callback Hell, which discusses the common practice of handling errors in callbacks. The article mentions that in Node.js, it is typical to designate the first argument of a callback function for error handling pu ...

angularjs controller module reference results in a page that fails to load

I am currently in the process of integrating the angular-wizard module into my Angular application. The Angular app was generated using yeoman. I installed the angular-wizard module using bower install angular-wizard and added it to my index.html file jus ...

Why doesn't package.json typically utilize the preset values stored in the .npmrc file?

Windows 10 x64 Based on the information found here, I created a file called C:\Users\bushm\.npmrc with the following content: author = "Andrey Bushman" However, when I run the command npm init -y in a new directory, I noticed that the pac ...

"How can I update a table in Flask using Chart.js and Pandas

I have developed a basic Flask application that includes a bar chart using Chart.js and a data table displayed below it. Check out the setup below: https://i.sstatic.net/QB6jQ.png (Live view: ) The bar chart I created counts the number of items for each ...

ALSO, various criteria

function findLogicalAND(){ let result; let index; for (index = 0; index < arguments.length; index++){ result = arguments[index] && arguments[index+1]; } return result; } console.log(findLogicalAND(true, true, false, false)); I want to r ...

Row index retrieval in Datatable is not possible following a search operation

I have successfully created a datatable and can retrieve the row index of the data before any search action is performed. dataArray=[ [1, "Name1"], [2, "Name2"], , [3, "Name23"], ]; var table = $('#tblName').DataTable( { ...

Constructing a MongoDB client using seed nodes

Let's consider a scenario where there is a replica set comprising of one primary P and three secondaries S1, S2, and S3. An application initializes a MongoDB client with this specific constructor. The list of seeds in this case includes {P, S1, S2} b ...

What's the best method for updating a div on a webpage to display the most current information from the database?

In my small blog project, I have implemented a viewcount feature that tracks the number of times a particular post has been viewed. However, the issue I am facing is that the value of viewcount does not update unless the entire page is refreshed. To addres ...

Could using 'require' in node.js lead to a memory leak issue?

I have been working on a program that experiences continuous heap growth. The program is quite simple - it repeatedly tries to load an external file (SyntaxError) using require. However, this external module fails to load due to a syntax error present in i ...