mongodb - MongoDB select distinct where not in select distinct
问题描述
在 mongoDB bd 中,我需要找到这些记录不在不同集合中的所有记录
假设我有 2 个收藏
1) 用户汽车
{
make: string,
user_id: objId
}
2) 自动制作
{
mfg: string,
make: string
}
我需要找到不属于“主品牌”列表的所有“品牌”
我想与这个 SQL 并行
SELECT DISTINCT
a.make
FROM
user_autos a
WHERE
a.make NOT IN (
SELECT DISTINCT
b.make
FROM
auto_makes b
)
请帮忙
解决方案
要实现这一点,您需要使用流水线阶段“查找”的聚合。查找确实在两个集合之间留下了连接。因此,显然“user_autos”的不匹配文档给出了一个空的嵌套数组“auto_makes”。然后用'make''group''user_autos'。以便生成“user_auto”文档列表。
你可以这样做如下。
db.user_autos.aggregate([
{$lookup:{
from:"äuto_makes",
localField:"make",
foreignField:"make",
as:"m"
}},
{$match:{
m:{$exists:false}
}},
{$group:{
_id:"$make"
}}
//if you want to get the distinct 'make' values as an array of single
//document, add another $group stage.
{$group:{
_id:"",
make_list:{$addToSet:"$_id"}
}}
])
访问https://docs.mongodb.com/manual/reference/operator/aggregation/group/, https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
推荐阅读
- python - 如何在for循环中填充熊猫数据框列
- flutter - Flutter:如何制作圆润的 PopupMenuButton 的 InkWell?
- docker - Gunicorn 在 Kubernetes 上的 Docker 映像中运行时不断引导工作人员
- python - 导入 pandas 时出现 C 扩展错误
- razor - 在 VS 2017 中打开 VS 2013 解决方案。现在 Razor 智能感知不起作用
- wordpress - WordPress允许在编辑时提交以供编辑审阅
- python - 解码 Django POST 请求正文
- spring - antMatchers 用于路径列表
- python - 比较两个列表并在发生更改时打印出来
- angularjs - 如何将 ng-if 逻辑写入控制器