在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个集合中存在的用户。

我能想到的一种方法是循环。

collection1中的每个用户,

在第2、3、4、5中查询他的ID或名称。

如果ID都在所有集合中,请记录其ID。

否则,跳过。

然后转到下一个用户。

我觉得这种方法不是很有效。使用MongoDB聚集方法可能会有更好的方法。

对这种情况有什么建议吗?或者我应该只使用循环?

在您在所有5个集合中搜索一个普通用户时,我们将在用户1集合中查询并使用$ Lookup并加入所有其他4个集合。这是肯定会起作用的查询建议。

所有用户集合的架构与您上面提到的架构相同:名称和工作字段。

db.getCollection('user1').aggregate({ "$facet": { "presentInAllCollections": [{ "$lookup": { "from": "user2", "localField": "name", "foreignField": "name", "as": "User2" } }, { "$lookup": { "from": "user3", "localField": "name", "foreignField": "name", "as": "User3" } }, { "$lookup": { "from": "user4", "localField": "name", "foreignField": "name", "as": "User4" } }, { "$lookup": { "from": "user5", "localField": "name", "foreignField": "name", "as": "User5" } }] } }, { $project: { "foundUser": { $filter: { input: '$presentInAllCollections', as: 'arrayElement', cond: { "$and": [{ $ne: ['$$arrayElement.User2', []] }, { $ne: ['$$arrayElement.User3', []] }, { $ne: ['$$arrayElement.User4', []] }, { $ne: ['$$arrayElement.User5', []] } ] } } } } })

您可以加入所有5个用户集合以获取常见的用户ID。为此,您必须使用聚合管道的$查找功能。

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

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

最新更新