What is the best way to choose a two-tier data structure in MongoDB?

I am currently in the process of creating an e-commerce application with a two-level product type system. For data storage, I have opted to use MongoDB and my chosen programming language is TypeScript.

Here is the model I am using:

class ProductTypeModel {
    _id: ObjectID;
    name: string;
    sort: number;   // sort
    status: number; // enable | disable
    children: Object[]; // sub types, like [{ _id: ObjectID('xx', name: 'xx', sort: xx, status: xx) }]
    create_time: Date;
    update_time: Date;
}

If we have data like this:

{
    "_id" : ObjectId("5b8fe56218de48345a6b7079"),
    "create_time" : ISODate("2018-09-05T14:17:06.912Z"),
    "update_time" : ISODate("2018-09-05T14:17:06.912Z"),
    "name" : "Books",
    "sort" : 0,
    "status" : 1,
    "children" : [
        {
            "_id" : ObjectId("5b8fe56218de48345a6b7075"),
            "name" : "Computer",
            "sort" : 1,
            "status" : 1
        },
        {
            "_id" : ObjectId("5b8fe56218de48345a6b7076"),
            "name" : "Math",
            "sort" : 2,
            "status" : 0
        },
        {
            "_id" : ObjectId("5b8fe56218de48345a6b7077"),
            "name" : "Novel",
            "sort" : 3,
            "status" : 1
        }
    ]
}

What would be the best way to select all types and child types where status=1 ?

At present, my approach involves selecting main types first and then programmatically excluding any child types with a status of 0. Is there a more efficient method for achieving this?

Answer №1

$redact aggregation stage is the solution you need:

    db['03'].aggregate(
    [
        {
            $redact: {
                $cond: {
                      if: { $eq: [ "$status", 1 ] },
                      then: "$$DESCEND",
                      else: "$$PRUNE"
                    }
            }
        },
    ],
);

Here is the output after applying the redact aggregation stage:

{ 
    "_id" : ObjectId("5b8fe56218de48345a6b7079"), 
    "create_time" : ISODate("2018-09-05T16:17:06.912+0200"), 
    "update_time" : ISODate("2018-09-05T16:17:06.912+0200"), 
    "name" : "Books", 
    "sort" : NumberInt(0), 
    "status" : NumberInt(1), 
    "children" : [
        {
            "_id" : ObjectId("5b8fe56218de48345a6b7075"), 
            "name" : "Computer", 
            "sort" : NumberInt(1), 
            "status" : NumberInt(1)
        }, 
        {
            "_id" : ObjectId("5b8fe56218de48345a6b7077"), 
            "name" : "Novel", 
            "sort" : NumberInt(3), 
            "status" : NumberInt(1)
        }
    ]
}

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

How to validate using two distinct mongoose instances

As a newcomer to mongoose and nodejs, I am facing an issue with two unique fields in mongoose. How can I properly validate them? Below is the code snippet: model var userSchema = new Schema({ local:{ email:{type:String,required:true,unique:tr ...

Error encountered when using Redis data type in Typescript

Hello, I'm currently attempting to implement Redis on typescript but keep encountering this error with my code. I have installed "redis": "^4.0.4", "@types/redis": "^4.0.11". How can I resolve this issue? const idUser: string Argument of type '[s ...

Navigating an array using ngFor and encountering an error message saying, "Identifier not specified"

While using ngFor to iterate through an array, I encountered the following error message: "Identifier 'expenseitem' is not defined. The component declaration, template variable declarations, and element references do not contain such a memb ...

Retrieve form input from a different component's form using React Hook Form

Currently, I am facing an issue with two React components that contain identical form fields. The challenge is to synchronize a checkbox in one component with the input from the form in the other component when it is checked. This functionality is similar ...

Tips for handling user click events in Angular 2?

In Angular2, I am facing an issue with two components. When a user clicks a button in component1, a method is triggered that stores data in the shared service to a variable. However, component2's ngOnInit() method initializes this variable to undefine ...

Is Materialized view supported by Azure Cosmos DB for Mongo?

Our current project requires the implementation of On-Demand Materialized Views for automatic updates in order to optimize our analytics dashboard performance. We have been using this feature successfully with Atlas Mongo, but we are uncertain if it is ava ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Angular 2 Ahead-of-Time compiler: all clear on the error front, yet a nagging feeling of

I've spent the last 72 hours trying to figure out how to make Ahead-of-Time compilation work for my Angular 2 rc.6 application. Currently, my application runs smoothly using Just-in-Time compilation. I've made sure to install all necessary depe ...

What is the process for defining the default landing page route in Angular routing?

My application currently has only one route, and I want it to start with the URL http://localhost:4200/specialtyQ. However, my application is not loading properly. The code snippet below is what I am using to try to achieve this. How can I correct the URL ...

Struggling with inserting data into MongoDB within my MERN application

I am currently developing a MERN app that allows users to create tasks and collaborate with others. To start my backend, I ran the nodemon index.js command in the git bash terminal. However, every time I try to send POST requests for data, I encounter an e ...

Utilizing WebWorkers with @mediapipe/tasks-vision (Pose Landmarker): A Step-by-Step Guide

I've been experimenting with using a web worker to detect poses frame by frame, and then displaying the results on the main thread. However, I'm encountering some delays and synchronization issues. My setup involves Next.js 14.0.4 with @mediapip ...

Enhancing mongoose find queries in Node.js with dynamic conditions using both AND and OR operators simultaneously

I've been experimenting with adding dynamic conditions using the Mongoose library. var and_condition = { $and: [] }; var or_condition = { $or: [] }; and_condition.$and.push ({ "doc_no" : /first/i }) or_condition.$or.push ({ "doc_type" : /third/i } ...

How do I transition to the backup node from the primary source?

Currently, my replicaset consists of 3 nodes. The primary node is named n1 and is running on port 27018, while the secondaries are named n2 running on port 27019 and n3 running on port 27020. I am trying to switch from the primary node to any secondary no ...

Updating a Meteor Template Element at regular intervals using an Interval

Hey everyone, I'm just getting started with Meteor. My goal is to periodically update an element (let's say {{title}}) that comes from a collection, fetching the next title every 20 seconds or so. In regular ajax, it's easy to write a funct ...

Displaying products with the active status set to 0 when utilizing the select feature in Angular

I need help displaying only data where "active" is set to 0. The data is retrieved in JSON format as shown below: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "h_id": "1", "active": 0, "d ...

Dynamically remove a MongoDB entry with precision

I'm having trouble deleting an entry in MongoDB based on the id variable. Even when I pass the id as a parameter to the method, it doesn't seem to work. I've double-checked the variable inside the method and I'm confident that it has th ...

Tips for determining if an array of objects, into which I am adding objects, contains a particular key value present in a different array of objects

I've been working on this and here is what I have tried so far: groceryList = []; ngOnInit() { this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => { this.loadedRecipes = receivedData.recipes; }); } onCheckRecipe(e) { ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome. l ...