【发布时间】:2021-04-11 00:05:34
【问题描述】:
问题定义:
我们有 2 个集合 User(存储用户数据)和 UserTransactions(存储用户完成的交易)。用户有 2 个usertypes“父母”和“学生”。
用户架构
{
_id : ---
name : String
usertype : String // parent/student
studententity : [] // It will store _id of related students from same document
}
UserTransaction 架构
{
_id : ---
ref_id: // id of parent who is doing transaction
}
我们需要获取的数据包括
- 所有家长名单
- 家长下的学生名单
- 如果父母完成了“任何”交易。
我们可以通过运行查询轻松获得第一个和第二个条件
User.find({ "usertype": { $eq: "parent" } })
.populate("studententity")
但我们还想获得有关父母是否进行过“任何”交易的信息。获取这些数据的最佳方式是什么?
我的预期结果是这样的
{
"usertype": "parent",
"studententity": [
{
"usertype": "student",
"_id": "5f8a6d0900e0030c7031d56a",
"name": "Adya"
},
{
"usertype": "student",
"_id": "5f9bb96fdf44b931b40c6043",
"name": "Aruja"
}
],
transactionflag : true // a flag that signifies transaction is done
}
【问题讨论】:
标签: mongodb mongoose mongodb-query aggregation-framework