首页 > 解决方案 > 获取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 循环?

标签: mongodbmongoosenosql

解决方案


您可以加入所有 5 个用户集合以获取公共用户 ID。为此,您必须使用聚合管道中的 $lookup 函数。

userCollection1.aggregate([{
  $lookup:{
    from:"userCollection2", 
    localField:"id", 
    foreignField:"id",
    as:"alias_name"
     }
   }
 ]
)

这将返回两个集合中的所有匹配文档。


推荐阅读