mongodb - 如何在MongoDB中选择两级数据结构?
问题描述
我正在开发一个具有两级产品类型的在线购物应用程序。现在我使用 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
. 有更好的方法吗?
解决方案
$redact 聚合阶段这将完成这项工作:
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)
}
]
}
推荐阅读
- go - 如何让进程认为输出到终端?
- spring - 在 spring 5.2.3 版本中没有触发 Quartz 调度程序作业,有什么建议吗?
- c# - C# - SQL - 将 rowsCount 动态添加到数据模型
- batch-file - 我们是否有命令在 Windows 命令提示符中删除目录的所有文件和目录
- python - 每次在循环中调用 Python 函数参数时,如何更新它?
- r - 根据 R 中的 id 和 year 列创建增量列 year
- reactjs - 如何发送带有查询的 Apollo 请求(graphql)?
- javascript - 确定某物是否是 JavaScript 中的普通对象的方法
- laravel - Laravel 8 中的 Route::get 格式
- java - mockito spy 没有像我预期的那样行事