Reputation: 11168
I have a simple data structure that defines people and their friends.
{
id: 0,
name: 'a',
friends: [1,2,3]
}
I need to find the common friends of two people. I managed to use the aggregation pipleline get the friends array into an array.
{ "_id" : 0, "friends" : [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ], [ 0, 1, 2 ] ] }
So the friends field is a nested array, and I want to get the intersection of its elements.
I tried to use the $setIntersection
operation, however I found it does not accept a variable of an array, it only accepts an array of variables. So I have to use something like this to get the result.
{
$project: {
commonFriendIds: {
$setIntersection: [
{ $arrayElemAt: ["$friends", 0] },
{ $arrayElemAt: ["$friends", 1] }
]
}
}
}
It looks ugly, and I have to modify the code to if I need to get the common friends of 3 or more people.
Is there's a better way to accomplish this?
Upvotes: 2
Views: 967
Reputation: 46441
You can use $reduce
aggregation operator. Now It will provide you the intersection for all the nested arrays inside the friends
array.
db.collection.aggregate([
{ "$project": {
"commonFriendIds": {
"$reduce": {
"input": "$friends",
"initialValue": { "$arrayElemAt": ["$friends", 0] },
"in": { "$setIntersection": ["$$this", "$$value"] }
}
}
}}
])
Upvotes: 4