来自嵌套数组 MongoDB 的项目对象
[
{
"_id": "grandParentId",
"types": [
{
"_id": "parentId",
"files": [
{
"url": "1.example.com",
"_id": "1childId"
},
{
"url": "2.example.com",
"_id": "2childId"
}
]
}
]
}
]
cond: { _id: 2childId }
预期输出:
{
"url": "2.example.com",
"_id": "2childId"
}
问题 2:这是一个好方法还是我应该使用循环来获得所需的输出?
[
{
"_id": "grandParentId",
"types": [
{
"_id": "parentId",
"files": [
{
"url": "1.example.com",
"_id": "1childId"
},
{
"url": "2.example.com",
"_id": "2childId"
}
]
}
]
}
]
cond: { _id: 2childId }
expected output:
{
"url": "2.example.com",
"_id": "2childId"
}
question 2: is this a good approach or should I just use loops to get the desired output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用聚合
$unwind
和$project
在 mongoPlayground< 进行测试/a>
useing aggregate
$unwind
and$project
test it at mongoPlayground
我确信还有其他方法,但您可以使用 mongo 聚合框架:
第一个$match 过滤器
$match
只是过滤与您的条件匹配的文档。$unwind
使用两次来解构不同的数组。$replaceRoot
将输入文档替换为指定文档(在本例中为子文档,files
)和最终的files 我们之前根据您的情况解构的数组。第一个
$match
只是出于性能原因,您可以根据需要删除它。来了解阶段的工作原理
您可以在 https://mongoplayground.net/p/hoz24xP_BNV查看 mongo 聚合框架 如果您想了解更多信息,请参阅文档(https://docs.mongodb.com/manual/aggregation/)
I'm sure that there are other ways, but you can use mongo aggregation framework:
The first
$match
is just to filter documents which match with your condition.$unwind
are used two times to deconstruct the different arrays.$replaceRoot
replaces the input document with the specified document (in this case subdocument,files
) and final$match
filtersfiles
arrays that we deconstructed previously, based on your condition. First$match
is just for performance reasons, you can delete it if you want.You can see how stages works in https://mongoplayground.net/p/hoz24xP_BNV
See mongo aggregation framework documentation if you want to learn more about it (https://docs.mongodb.com/manual/aggregation/)