在mongoDB bd中,我需要找到所有不在不同集合中的记录
说我有2个收藏夹
1)user_autos
{
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
)
请帮助
答案 0 :(得分:1)
要实现此目的,您需要在流水线阶段“查找”中使用聚集。 查找确实使两个集合之间保持联接。因此,很明显, 'user_autos'提供一个空的嵌套数组'auto_makes'。然后将“ 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/