node.js - 按猫鼬中的孙子属性过滤
问题描述
我对猫鼬很陌生,我想知道是否可以根据孙子属性进行过滤。我到处寻找,但我无法根据我正在尝试做的事情找到类似的问题。这是场景:
想象一下,我有一个这样的数据库:
db={
"parents": [
{
"_id": ObjectId("5a834e000102030405000000"),
"child": ObjectId("5a934e000102030405000000")
},
{
"_id": ObjectId("5a834e000102030405000001"),
"child": ObjectId("5a934e000102030405000001")
},
{
"_id": ObjectId("5a834e000102030405000002"),
"child": ObjectId("5a934e000102030405000002")
},
],
"children": [
{
"_id": ObjectId("5a934e000102030405000000"),
"grandchild": ObjectId("5a734e000102030405000000")
},
{
"_id": ObjectId("5a934e000102030405000001"),
"grandchild": ObjectId("5a734e000102030405000001")
},
{
"_id": ObjectId("5a934e000102030405000002"),
"grandchild": ObjectId("5a734e000102030405000002")
}
],
"grandchildren": [
{
"_id": ObjectId("5a734e000102030405000000"),
"name": "grandchild1"
},
{
"_id": ObjectId("5a734e000102030405000001"),
"name": "grandchild2"
},
{
"_id": ObjectId("5a734e000102030405000002"),
"name": "grandchild3"
}
]
}
我想返回所有有一个孙子名字为“grandchild1”的父母。
类似的东西
$match: {
"child.grandchild.name": "grandchild1"
}
所以只有这个父级会在结果中返回——
[{
"_id": ObjectId("5a834e000102030405000000"),
"child": ObjectId("5a934e000102030405000000")
},]
解决方案
在有人回答之前我找到了答案...
https://mongoplayground.net/p/w1kw58PzCyk
db.parents.aggregate([
{
$lookup: {
from: "children",
localField: "child",
foreignField: "_id",
as: "child",
}
},
{
$addFields: {
child: {
$arrayElemAt: [
"$child",
0
]
}
}
},
{
"$lookup": {
from: "grandchildren",
localField: "child.grandchild",
foreignField: "_id",
as: "grandchild",
}
},
{
$addFields: {
grandchild: {
$arrayElemAt: [
"$grandchild",
0
]
}
}
},
{
$match: {
"grandchild.name": "grandchild1"
}
}
])
推荐阅读
- android - 为什么我的 Android Studio 语言变得很奇怪?
- c# - URL 重定向到变量
- c - 我试图在 VS 中运行一个简单的 c 代码,但这表明,该怎么办?
- angular - Angular 新的日期范围过滤器错误?
- windows - 无法使用 docker-compose 将 docker 文件夹挂载到主机中
- python - Python中的静态方法可以访问/修改类变量吗?
- mongodb - 如何在 MongoDB 中投影 addFields 属性
- javascript - 使用 jQuery 将常量值与实际值进行比较
- python - 如何在 DynamoDB 中查询条件属性
- javascript - Websocket 事件在 React 应用程序中接收旧的 redux 状态