Ensure that all fields in the document are included at every level according to their respective values

How can I create a role-based menu where users with permission to view forms like cavoucher and puvendor will only see matched content along with the parent element? I only have the form names, which could be defined anywhere in the document.

   [ { 
"_id" : ObjectId("57ef642fd4f27bb41b697314"), 
"menuDesc" : "Cash Module", 
"formName" : "", 
"subMenu1" : [
    {
        "menuDesc" : "Setup", 
        "formName" : "", 
        "subMenu2" : [
            {
                "menuDesc" : "Setup Bank Details", 
                "formName" : "cabank", 
            }
        ]
    }, 
    {
       "menuDesc" : "Vouchers", 
        "formName" : "", 
        "subMenu2" : [
            {
                "menuDesc" : "Maintain Cash Voucher", 
                "formName" : "cavoucher", 
            }, 
            {
                "menuName" : "Paid Voucher", 
                "menuDesc" : "Maintain Paid Voucher", 
                "formName" : "capaidvchr", 
            }
        ]
    }
    ]
},
{ 
"_id" : ObjectId("57ef6464d4f27bb41b697316"), 
"menuDesc" : "Purchase Module", 
"formName" : "", 
"subMenu1" : [
    {
        "menuDesc" : "Maintain Vendors", 
        "formName" : "puvendor" 
        }
]
}] 

The desired result is:

    [{ 
"_id" : ObjectId("57ef642fd4f27bb41b697314"),
"menuDesc" : "Cash Module", 
"formName" : "", 
"subMenu1" : [
    {
        "menuDesc" : "Vouchers", 
        "formName" : "", 
        "subMenu2" : [
            {
                "menuDesc" : "Maintain Cash Voucher", 
                "formName" : "cavoucher", 
            }
        ]
    }
  ]
 },{ 
"_id" : ObjectId("57ef6464d4f27bb41b697316"), 
"menuDesc" : "Purchase Module", 
"formName" : "", 
"subMenu1" : [
    {
        "menuDesc" : "Maintain Vendors", 
        "formName" : "puvendor" 
        }
]
}}

I am unsure at which level the value matches. Can you suggest any possible solution?

Answer №1

To accomplish this task in MongoDB, you can utilize the powerful aggregation pipeline.

In your specific scenario, where there are two nested arrays - subMenu1 and subMenu2, you would first need to use the $unwind operator on both arrays and then employ the $match stage to obtain the desired outcome.

Below is a sample Mongo Shell query that demonstrates this:

db.collection.aggregate([
    {$unwind:"$subMenu1"}, 
    {$unwind:"$subMenu1.subMenu2"},
    {$match:{"subMenu1.subMenu2.formName":"cavoucher"}}
 ])

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

Troubles with Uploading Images and Validating Forms in Next.js 14 using Shadcn, Zod, and React Hook Form

I'm currently experiencing challenges with image upload and form validation in my Next.js 14 application using Shadcn, Zod, and React Hook Form. Specifically, I have a user profile creation form where I encounter the following issues: Image Upload Pr ...

Struggling to find a way to compare Object Ids with handlebars?

I am new to using Handlebars and currently facing an issue with comparing user _id with the logged-in user id. I have stored data in MongoDB using mongoose and tried using a helper from StackOverflow, but it doesn't seem to compare the values correctl ...

Ways to verify if a JsonObject contains a particular string

I am currently working with a Json Object that contains menus and submenus. However, there are instances where there are no submenus present. How can I determine if the JsonObject includes a specific String (Submenu) without encountering a JsonException? ...

Tips for retrieving selected items in an array object

Within my UI, I have a select field that, on change, populates corresponding data in a div with nested ul and li elements. What I am attempting to achieve is to convert the selected items within the list (which include checkboxes) into an object of arrays ...

I rely on Cordova for my app development, but it tends to lag when I try to capture photos or videos

When I searched on Google, I came across a message mentioning "supportedVideoModes" as an option for setting video properties. However, I am unsure about how to properly use this option and what properties it entails. Can you provide some guidance on thi ...

NPM packages installed on a global level are not being detected

Recently, I experienced a system crash that led me to delete some files in an attempt to fix the issue. Among those files may have been ~/.profile. Since restoring my system, I've noticed that my globally installed npm packages are no longer functioni ...

Building a simple messaging platform with the power of Socket.io and Node.js

After following the guide at http://socket.io/get-started/chat/, I attempted to create a basic chat application. However, upon running npm install --save socket.io I encountered the error message below. How can I resolve this issue? npm WARN package.jso ...

The Prisma seed encountered an issue where the node reported a failure in the Unique constraint

I am facing an issue while trying to seed my database, as I encountered the following error: Unique constraint failed on the constraint: Figures_table_manufacturerID_key I have tried various solutions to fix this problem, but nothing seems to be working. ...

Can you explain the convention for boolean parameters in JavaScript or React?

Currently working with React and seeking to implement a basic setter using useState. For instance: const [isOpen, setIsOpen] = useState(false); const handleIsOpen = (value:boolean) => { setIsOpen(value) } I'm unsure about the most appropriate ...

Issues with the functionality of a jQuery slider after converting it to vanilla JavaScript

While working on a slider project, I wanted to steer clear of using jQuery and instead focus on vanilla JavaScript for the implementation. The original jQuery code snippet that needed conversion: setInterval(function() { var $curr = $('#slider1 in ...

Reverse the action if the user selects "cancel" when asked to confirm using the `confirm()` function

I created a handy feature that allows you to drag items from a list to a trash can for deletion. When you click "ok", the item is successfully removed as intended. However, if you hit "cancel" on the confirmation popup, the item still goes into the trash ...

Combining and adding multiple JSON arrays in PHP

I am faced with the task of merging/joining multiple JSON strings that contain arrays, and I am unsure of the best approach to take: Initial array of JSON strings (referred to as $rrDatas in my example below): Array ( [0] => {"asset":[1],"person": ...

What is the process of extracting a URL and inputting it into a form to enhance

Can anyone help with extracting a specific value (TEXT) from a URL and automatically paste it into an input form field? For example, if the URL is domain.com/page?code=123abc, I need to grab the code (in this case, 123abc) and have it automatically popula ...

What could be the reason behind encountering a "Cannot return null for non-nullable field" error while attempting a mutation?

Exploring (Apollo) GraphQL on the server side has presented me with a puzzling issue. I have been attempting to register a user, but I keep encountering the error documented in the linked image below. What could be causing this problem? Let's disregar ...

"Utilizing Webpack dev server with React to display directory listing only when the application is in operation

When I try to access my project through webpack-dev-server, all that displays in the browser is the directory listing. Even though I can navigate to the files and view them, the actual application doesn't seem to be running. On the other hand, when I ...

What is the best way to toggle the visibility of a dynamically created HTML element in ASP.NET?

I'm working on a program that displays two different prices depending on whether the user is registered or not. Registered users will see both the normal price and the discounted price, while unregistered users will only see the normal price. I need t ...

Utilizing the nuxt $store in a Dynamic Component

I'm currently working on a Promise-based modal component that allows for specifying a component as the body of the modal itself. My approach to achieving this was by using a dynamic component inside the modal template. However, when working within a N ...

Incorrectly accessing end points

After submitting my project on fetching popular movies data to Udacity, I received a review that pointed out a small issue. The reviewer mentioned that while the endpoints are implemented perfectly and return accurate results with each request, there is a ...

Exploring the wonders of retrieving JSON data in PHP through an Ajax request

A front-end developer is sending an array of data formatted as a JSON object using an Ajax call. The JSON object structure is shown below: { "name": " Test Name ", "image_url": "test URL", "include": [ "1" ], "dimension": [ null ], "media_type" ...

The communication between a Firefox XUL extension and a webpage

Currently developing a Firefox XUL extension and in need of incorporating interaction between the web page and the extension. For instance, whenever a link is clicked on the page, I would like to trigger a function within the XUL extension. Is there any k ...