mongodb - 获取MongoDB中几个集合的公共id?
问题描述
我在 Mongodb 中有几个用户集合。如下:
userCollection1:
User1: {name:xxx,
id:xxx
<other fields>}
User2: {name:xxx,
id:xxx
<other fields>}
..other users..
userCollection2:
User1: {name:xxx,
id:xxx
<other fields>}
User3: {name:xxx,
id:xxx
<other fields>}
..other users..
userCollection3:{} //All same scheme as previous collection
userCollection4:{}
userCollection5:{}
每个都是不同用户列表的单独集合。现在我正在尝试获取所有这 5 个集合中存在的用户。
我能想到的一种方法是for循环。
对于 collection1 中的每个用户,
在集合 2、3、4、5 中查询他的 id 或 name。
如果id在所有集合中,记录他的id。
否则,跳过。
然后转到下一个用户。
我觉得这种方法效率不高。使用 mongodb 聚合方法可能有更好的方法。
对这种情况有什么建议吗?或者我应该只使用 for 循环?
解决方案
您可以加入所有 5 个用户集合以获取公共用户 ID。为此,您必须使用聚合管道中的 $lookup 函数。
userCollection1.aggregate([{
$lookup:{
from:"userCollection2",
localField:"id",
foreignField:"id",
as:"alias_name"
}
}
]
)
这将返回两个集合中的所有匹配文档。
推荐阅读
- powershell - PowerShell 如何抑制错误消息
- php - 从字符串中删除通配符
- hbase - Apache phoenix:创建 phoenix 表映射到现有的 hbase 表
- scala - FS2 将资源(或效果)作为状态传递
- ios - 带有表单和列表的 SwiftUI 内存泄漏
- java - 从 LinkedHashMap 获取有序流
- python - 如何在 python 的 ODE 中找到优化的参数?
- java - 从 Firestore 数据库中检索 GeoPoint 数组添加地图多边形
- c# - 在 C# 中运行时类型不匹配时抛出的适当异常是什么
- html - 如何删除背景图像失真