zhm
zhm

Reputation: 3641

How to select two-level data structure in MongoDB?

I'm developing an online shopping application, which has two-level product type. Now I'm using MongoDB to store it. My programming language is TypeScript.

My model is like below:

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 below:

{
    "_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
        }
    ]
}

How can I select types and children types with status=1 ?

My current solution is to select base types first, and traverse to exclude children whose status is 0. Is there a better way to do it?

Upvotes: 0

Views: 45

Answers (1)

matthPen
matthPen

Reputation: 4353

$redact aggregation stage this will do the job:

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

output :

{ 
    "_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)
        }
    ]
}

Upvotes: 1

Related Questions