如何在MongoDB中选择两级数据结构?

问题描述 投票:0回答:1

我正在开发一个具有两级产品类型的在线购物应用程序。现在我使用MongoDB来存储它。我的编程语言是TypeScript。

我的模型如下:

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;
}

如果我们有以下数据:

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

如何使用status=1选择类型和子类型?

我目前的解决方案是先选择基类型,然后遍历以排除status0的子项。有没有更好的方法呢?

mongodb typescript
1个回答
1
投票

$redact aggregation stage这将完成这项工作:

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

输出:

{ 
    "_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)
        }
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.