mongodb - mongodb:按条件获取嵌套数组的元素
问题描述
需要按条件获取嵌套数组的元素。产地收藏:
[
{
code: 134,
bindings: [
{
devId: "71156ce8-ac2b-4282-9f5a-10133441057c",
userIds: ["9d300b89-29c0-45a8-a4d3-019cfc8f1c7b"]
},
{
devId: "ca33efa1-ec27-4ee1-8117-8b8ab29c1790",
userIds: ["73e5af2f-fe01-41a3-bebd-6bab895cab58"]
},
{
devId: "a03f5fbd-f279-4182-bfb6-33aba9de5751",
userIds: ["dc0c5e59-ef1a-44b9-843b-a4ea73bbed2e"]
}
]
}
]
我尝试使用聚合函数:
db.trigger.aggregate([
{ $match: { _id: "134" } },
{ $unwind: "$bindings" },
{ $match: { "bindings.devId": "ca33efa1-ec27-4ee1-8117-8b8ab29c1790" } },
{ $project: { _id: 0, dateset: 1 } },
{ $out: "bindings" }
]);
但它没有给出预期的结果。Сan有人告诉我我做错了什么?
解决方案
您可以尝试以下聚合,$replaceRoot将嵌套文档提升到根级别:
db.collection.aggregate([
{
$match: { code: 134 }
},
{
$unwind: "$bindings"
},
{
$match: { "bindings.devId": "71156ce8-ac2b-4282-9f5a-10133441057c" }
},
{
$replaceRoot: { newRoot: "$bindings" }
}
])
推荐阅读
- angular - 表单反应返回空
- c# - 带有服务帐户(不是用户帐户)的 SQL Server 集成安全性
- python - how to get a numerical result for exp sympy python
- swift - 无法从 GitLab 访问我的 Swift 包
- amazon-web-services - 从现有安装的 AWS ALB 入口控制器 (v1) 迁移到新的 AWS 负载均衡器控制器 (v2) 的问题
- python - FastAPI - CORS 和 slowapi
- sparql - Wikidata SPARQL 按语言过滤字段值
- mysql - XAMPP ECONNREFUSED 用于 localhost:3306
- sql - TSQL Pivot or Estimate Model Replication
- pyspark - PIL 与 PySpark 中的 Base64 jpg 图像