2

我有一个简单的数据结构来定义人和他们的朋友。

{
  id: 0,
  name: 'a',
  friends: [1,2,3]
}

我需要找到两个人的共同朋友。我设法使用聚合管道将朋友数组放入数组中。

{ "_id" : 0, "friends" : [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ], [ 0, 1, 2 ] ] }

所以friends字段是一个嵌套数组,我想得到它的元素的交集。

我尝试使用该$setIntersection操作,但我发现它不接受数组变量,它只接受变量数组。所以我必须使用这样的东西来获得结果。

{
  $project: {
    commonFriendIds: {
      $setIntersection: [
        { $arrayElemAt: ["$friends", 0] },
        { $arrayElemAt: ["$friends", 1] }
      ]
    }
  }
}

它看起来很难看,如果我需要获得 3 个人或更多人的共同朋友,我必须修改代码。

有没有更好的方法来实现这一点?

4

1 回答 1

3

您可以使用$reduce聚合运算符。现在它将为您提供数组内所有嵌套数组的交集friends

db.collection.aggregate([
  { "$project": {
    "commonFriendIds": {
      "$reduce": {
        "input": "$friends",
        "initialValue": { "$arrayElemAt": ["$friends", 0] },
        "in": { "$setIntersection": ["$$this", "$$value"] }
      }
    }
  }}
])

Mongo游乐场

于 2020-01-16T05:05:21.607 回答