Uncovering the Secrets of Retrieving Nested Objects with MongoDB and Mongoose

I have a collection of documents stored in my mongodb database, each structured like this:

{ 
    "current" : 
    { 
        "aksd" : "5555", 
        "BullevardBoh" : "123" 
    }, 

    "history" : 
    { "1" : { 
            "deleted" : false, 
            "added" : false, 
            "date" : "21-08-2014" 
            }
    }, 

    { "2" : { 
            "deleted" : false, 
            "added" : false, 
            "date" : "01-01-2013" 
            }
    }, 

    "_id" : ObjectId("53f74dad2cbfdc136a07bf16"), 
    "__v" : 0 
}

My goal now is to accomplish two tasks with my Mongoose/Express API.

  1. To query for all nested "current" objects in each document and retrieve them as JSON objects, such as:

    {"aksd":"5555","BullevardBoh":"123"},{..},{..}
    .

  2. To retrieve all history revisions (1,2...) where the "date" is before a specified date.

This setup represents a versioning system that I am implementing. I am also curious if MongoDB will index this data structure efficiently or if there might be a better alternative, perhaps using arrays within objects?

The following MongoDB query does not work:

db.ips.findOne({current.aksd: {$exists:true}});

Answer №1

It appears that the quotation marks were inadvertently left out within the field:

db.ips.findOne({current.aksd: {$exists:true}});

To correct this, the query should be structured as follows:

db.ips.findOne({"current.aksd": {$exists:true}});

Answer №2

Although Ritesh's response was a positive step, I was actually looking to extract the current object literal and its properties within the document rather than the entire document.

1.) Search for all nested "current" in each document

db.ips.find({"current":{$exists:true}}, {"current":1});

This query will return all nested documents that contain the specified literal:

{ "current" : { "aksd" : "5555", "BullevardBoh" : "123" }, "_id" : ObjectId("53f74dad2cb3dc136a07bf16") }
...

2.) Retrieve historical revisions where date is earlier than a given date:

db.ips.find({"history.date": {$lt: "01-01-2014"}},{history:{$elemMatch:{date: {$lt:"01-01-2014"}}}});

This query will display the desired nested date property(s):

{ "historie" : [  {  "date" : "01-01-2013",  "added" : false,  "deleted" : false } ], "_id" : ObjectId("53faf20f399a954b2b7736b6") }

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

Clicking on the (x) button element will eliminate the DOM node from a list

https://i.stack.imgur.com/GxVYF.png A value is being dynamically added to my page, and here is the code snippet: function favJobs(data){ number_of_jobs_applied = data.total_bookmarked; $('.bookmark-title').append(number_of_jobs_applied, " ...

Is the navigation component's loss of properties due to a React router error?

After implementing react router for the first time, I noticed that the props passed to my nav component get lost once a new route is rendered. It's like the items in the cart are disappearing when I click checkout, but reappear correctly when I go bac ...

Steps to import an excel file by clicking a button in an Angular application

Our project requires displaying an Excel file when a menu button is clicked. https://i.sstatic.net/9tas1.png When a new tab is opened, I would like to showcase the Excel file that is saved on my personal computer. The format of the Excel file should resem ...

Having difficulty accessing a function within the SignalR connection function

I am currently facing an issue while trying to access a specific function within a SignalR connection function. Below is the code snippet showcasing the entire script for better understanding: $(function() { var chat = $.connection.chatHub; chat.c ...

Transitioning from pop-up modals to AngularJS JSON

I have a table with fields such as: product, lot, input1, input2. It is possible to clone a line or add a new line. The selection of the Product is based on a value from JSON data. The Lot selection initially stays empty and gets filled with sub-arrays rel ...

Modifying a Field's Value by Referring to a Different Field

I am working on developing a form that includes a dropdown menu for changing the aircraft type. Additionally, I want to incorporate another field named "Registrations" which will automatically update the available registration options based on the selected ...

Iterate over an array in PHP, extract JSON data from files with corresponding names, and then store the extracted JSON as properties

Apologies for the intricate title - describing my situation is quite challenging. This is JSON file Egg.json: {"1":{"name":"Egg"}} This is index.php: error_reporting(E_ALL); class Test { public $arrEgg; public $arrTypes = array("Egg"); pu ...

What is the best way to connect a directive's attribute to a dropdown menu in Angular.js?

Within a dropdown, I have a selection of templates that are connected to $scope.templates: [{"id":1, "name":"Test 1",{"id":2, "name":"Test 2"}]. Furthermore, there is a directive in place, <editor data-template="1"></editor> The goal is to ...

Identifying whether a Alphabet or a Digit has been Pressed - JavaScript

I understand that it is possible to detect if a key has been pressed and identify which key was pressed using JavaScript. In order to check if a key is down or pressed, jQuery can be utilized with ease: $( "#some id" ).keydown(function() or $( "#m" ). ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

Analyzing the data within two JSON files to determine if they are identical or not

I'm dealing with a vast collection of JSON files, each having a unique JSON structure. I'm trying to figure out how to compare the content in these JSON files using Python and determine whether they match or not. JSON file A; JSON file B; Match ...

The function window.close() does not close the pop-up window when called within the pop-up

I am facing an issue with a Customer Info form that contains an anchor tag "close" meant to close the current window. This customer form is displayed as a pop-up. Within this form, there is also a search button that triggers a pop-up for the search form co ...

Could someone help clarify this issue within a React project?

I've encountered an issue with a react task and I could use some clarification. // React is loaded and is available as React and ReactDOM // imports should NOT be used class Input extends React.PureComponent { render() { let {forwardedRef, ...ot ...

What is the best way to extract information from a JSON array using Gson?

Currently, I have obtained a json file with data structured in the following format: [ [ "name1", "age1", "gender1", url1 ], [ "name2", "age2", "gender2", url2 ], ... ] I am looking to parse this data and s ...

Showing JSON content in UITableView using Swift 4 along with Alamofire

Hi there, I'm a beginner in Swift and I could really use some help. I'm working on an app that parses JSON data in Swift and here's the code snippet I've put together: import UIKit import Alamofire import SwiftyJSON class ViewControll ...

Obtaining JSON data using PHP

Received JSON string from the API response {"accessTokenResponse":{"token":"562371e99fda4296a380547cb5bf9fab","token_type":"Bearer","expires_in_seconds":"77476","client_id":&qu ...

The rendering of code is often disrupted when utilizing the keyword const

I've been working my way through the Angular2 tutorial called Tour of Heroes and everything has been going smoothly up until this point. At the link above, I've encountered a problem. The code on the left is what the tutorial recommends, but fo ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

Securing and unscrambling the json file in a node.js environment

Is there a way to encrypt and decrypt a JSON file in node.js? I attempted to run this program and encountered an error stating that File password tty.setrawmode is not a function. Original text: { "production" : { "db" : { "database" : "my ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...