我正在开发一个在线购物应用程序,它具有两级产品类型。现在,我正在使用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
选择类型和子类型?
我当前的解决方案是首先选择基本类型,然后遍历以排除status
为0
的子代。有更好的方法吗?
答案 0 :(得分: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)
}
]
}