mongodb - 查询 MongoDb 聚合连接两个集合
问题描述
我需要查询 mongoDb 的帮助
所以我有两个收藏,比如
集合 A:
{someField: "123", anotherField: "456"},
{someField: "1234", anotherField: "4567"}
集合 B
{someField: "123", otherField: "789"}
带查询:
db.A.aggregate([
{
$lookup:
{
from: "B",
let: { someField: "$someField", otherField: "$otherField" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$someField", "$$someField" ] },
{ $eq: [ "$otherField", "789" ] }
]
}
}
},
],
as: "B"
}
}
])
我得到所有集合 A,其中 B 为空{someField: "1234", anotherField: "4567"}
我想要实现的是:
{someField: "123", anotherField: "456", b: {someField: "123", otherField: "789"}}
先感谢您
解决方案
这就是我删除空B
数组文档的方式:
db.A.aggregate( [
{
$lookup: {
from: "B",
localField: "someField",
foreignField: "someField",
as: "B"
}
},
{
$addFields: {
B: {
$filter: {
input: "$B",
cond: {
$eq: [ "$$this.otherField", "789" ]
}
}
}
}
},
{
$match: {
$expr: {
$gt: [ { $size: "$B" }, 0 ]
}
}
}
] ).pretty()
推荐阅读
- sql - 将 sys_refcursor 从函数传递到过程中的 sys_refcursor out 参数
- java - 与GIT中的Head进行比较时获取Java类的修改方法名称
- javascript - fetch 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头
- javascript - 如何使用 javascript 暂停 d3.js 模拟?
- c - 如何使用 scanf_s 读取多个字符?
- azure-devops - Azure管道如何在脚本等待用户输入时检测管道何时停止
- matlab - 符号和数字输入的写入函数
- git - 为什么`git clone --depth=1
` 某些带有 HTTP 500 的存储库失败? - ios - 使用 use_frameworks!在一个反应式项目上
- typescript - Angular8:formControlName 必须与父 formGroup 指令一起使用