首页 > 解决方案 > 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
    )

请帮忙

标签: mongodb

解决方案


要实现这一点,您需要使用流水线阶段“查找”的聚合。查找确实在两个集合之间留下了连接。因此,显然“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/


推荐阅读