Seeking out and showcasing a distinct item from an array in MongoDB - how can it be done?

I'm struggling with writing a mongo script for my app to retrieve and display the service logs for a specific vehicle. In this case, I have two users, each with multiple vehicles that have their own set of service logs. Despite my efforts, I haven't been successful in only displaying the serviceLogs entries from the second user with _id:"2" for the vehicle with _id:14. Below is a snippet of the sample data.

db.collection.insert(
{_id:"1",vehicles:[
{_id:11,make:"Mazda",model:"CX5",serviceLogs:[
{_id:110, "miles" : 7567,"service" : "Wipers replacement"}
]}]});

db.collection.insert(
{_id:"2",vehicles:[
{_id:12,make:"Mazda",model:"CX5",serviceLogs:[]},
{_id:13,make:"Chevy",model:"Sonic",serviceLogs:[]},
{_id:14,make:"Toyota",model:"Tacoma",serviceLogs:[
{_id:111, "miles" : 2134,"service" : "Brake pads replacement"},
{_id:112, "miles" : 5678,"service" : "VSS replacement"}
]}]});

Below are the queries I've attempted without much success.

db.collection.find({"_id": "2", vehicles: {$elemMatch: {make: "Toyota", model: "Tacoma"}}} ).pretty();
db.collection.find({"_id": "2", "vehicles.$.serviceLogs": {$elemMatch: {serviceLogs:{id: 111}}}})
db.collection.find({"_id": "2", vehicles: {$elemMatch: {serviceLogs:{id: 111}}}})

Expected output:

{
  "_id" : 111.0,
  "miles" : 2134.0,
  "service" : "Brake pads replacement"
}, 
{
  "_id" : 112.0,
  "miles" : 5678.0,
  "service" : "VSS replacement"
}

If you have any suggestions or solutions, they would be greatly appreciated. Thank you.

Answer №2

Even though the initial response didn't match my expectations, I received a query that not only provided the vehicle details but also included the service logs. This is more beneficial as it allows me to access information like the vehicle's make, model, and its entire service history. The query specified in this case will fetch data for only one vehicle based on the _id and vehicle._id. Below is an example of how to retrieve information for a vehicle with _id:"2".

db.collection.aggregate([
    { $match: { _id: "2" } },
    {
      $project: {
        vehicles: {
          $filter: {
            input: "$vehicles",
            as: "vehicle",
            cond: { $eq: ["$$vehicle._id", 14] }
          }
        },
        _id: 0
      }
    }
  ]).pretty()

The outcome of this query is described below:

{
    "vehicles" : [
            {
                    "_id" : 14,
                    "make" : "Toyota",
                    "model" : "Tacoma",
                    "serviceLogs" : [
                            {
                                    "_id" : 111,
                                    "miles" : 2134,
                                    "service" : "Brake pads replacement"
                            },
                            {
                                    "_id" : 112,
                                    "miles" : 5678,
                                    "service" : "VSS replacement"
                            }
                    ]
            }
    ]
}

With MongoDB's aggregate and $project, I can accurately extract the necessary data from the targeted vehicle. In my React application, below is a snippet of code demonstrating how I stored the retrieved vehicle data into React states.

API.getOneVehicleForUser(this.state.uid, this.state.vehicleId) // Invoking API call with user ID and desired vehicle ID
  .then(res => { // Assigning fetched data to React states upon successful API call
      this.setState({
        make: res.data[0].vehicles[0].make,
        model: res.data[0].vehicles[0].model,
        serviceLogs: res.data[0].vehicles[0].serviceLogs
      })
  .catch(err => console.log(err)); // Implement error handling strategies for unsuccessful API calls

this.state.serviceLogs represents an array containing all service logs associated with the vehicle. You can perform various actions with this data, such as counting the number of service logs (this.state.serviceLogs.length) or displaying individual logs based on miles and service type.

While this solution may not be perfect, it has proved to be efficient for my specific application requirements.

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

Sending JSON data from SignalR back to Knockout ViewModel

I'm struggling with my Knockout and SignalR implementation as a beginner. Although I can display JSON data in a debug element by databinding it to dashboard, I encounter undefined errors when trying more complex databinding. For example, the code sni ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

React, incorporating emojis within a dropdown menu

Recently, I've been developing a small game using React where players can customize settings before beginning. The game involves four players chasing different tokens on the map while avoiding the player designated as "it". Within my code, I have a r ...

Comparing the value of a variable inside a class with a global variable declared as let is not possible

I am facing an issue while trying to compare a variable named 'let hours' within my class. The comparison needs to be done in a separate function called 'utcChange' after clicking a button. I initially declared this variable at the begi ...

using http to handle a 404 error

This specific function is designed to fetch data under normal circumstances and to return a value of 0 in the event of a 404 error. function retrieveData(url) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); ...

What parameters should I include in an Ajax request to upload a file using SFTP in a JS + PHP setup?

I need the user to input a PDF or image file on my page, which will then be uploaded via SFTP using PHPSECLIB. Additionally, I want to transmit the file along with some additional data via ajax. var file = this.files[0]; alert('You ha ...

Showing events from MySQL database on Vue.js Fullcalendar

I am trying to fetch events from my MySQL database and pass them to my Vue component to be displayed on the FullCalendar. However, the event array is being populated with a full HTML document. Below is my EventController: public function getEvents() { ...

Combining Arrays in Node.JS and Converting to JSON

I have the code snippet below that executes several functions to retrieve different data. My goal is to create or append to an array in order to generate a new array which can then be JSON.stringify and sent to the Jade view. Currently, I am only able to o ...

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...

Directive isolated scope is encountering an undefined $scope variable

After searching through various Stack Overflow posts on the issue, I have tried different solutions but still can't get my directive to render. The goal is to pass an integer to my directive within an ng-repeat loop and display an emoji based on that ...

Tips for retrieving data from an event handler using a promise?

I'm currently developing a nodeJS application that utilizes the nodegit npm package. Following an example from their documentation, I have implemented a function that involves a chain of promises and resembles a JQuery event handler. Here is the code ...

The curious case of React and Redux: Why won't my value show up from the reducer even with mapStateToProps?

While working on my react project, I successfully integrated redux and set up a reducer containing an object with a key-value pair: "key: 'hello'". After importing it into my index.js file located in the reducers folder, I attempted to utilize it ...

What is the best way to allow a number to be editable when clicked on in a React application

Currently, I am trying to find a solution for making a number editable when clicked without having to use form inputs or other React libraries that don't fit my requirements. The provided screenshots showcase the desired interface. https://i.stack.im ...

obtaining selections from a dropdown menu and transferring them to an unordered list using jquery

Currently, I am in the process of developing a plugin that transforms select boxes into visually appealing elements. This transformation involves converting select boxes on a page into definition lists, where each definition description contains a nested u ...

Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example: { "totalCount":"4", "data":[ {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...}, {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","even ...

methods for sharing real-time data between parent and child components in Angular versions 2 and above

When working with Angular, we are familiar with parent to child communication using the @Input decorator. However, the challenge arises when we need to pass dynamic data from the parent to the child component. Imagine having a 'name' property def ...

Unable to change the value of a variable in a function in AngularJS

Calling all developers for assistance! I am experiencing an issue with updating a value dynamically inside an AngularJS controller that is being passed to an HTML tag. Everything works perfectly when updating the value outside of a function: var app = angu ...

Differentiating between the simple and luxurious text editing features available in the TinyMce editor

I am currently utilizing the TinyMCE editor to enhance the appearance of a textarea field where users can input comments. My goal is to offer two options for users: one for plain text and the other for a rich text editing experience. When a user selects th ...

Trouble with pymongo count_document() function when using datetime values

Hello, I am currently working on querying data from MongoDB using Python 3.8, Django 4.2.2, Arrow 1.2.3, PyMongo 3.13.0. The MongoDB setup is serverless. Here is the filter object I am using: filter['created_at']={ '$gte': arro ...

Creating a "return" button for an editing form in AngularJS Datatables with the help of a form directive

Using AngularJS Datatables, I implemented a grid with additional "edit" and "delete" buttons in the last column. How is the grid/table rendered? HTML <!-- Required CSS and JS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/li ...