вы можете использовать $setIntersection
db.t67.aggregate([
//{$match : {}} add filter criteria to filter documents
{$group : {_id : null, array : {$push : "$array"}}},
{$project : {_id :0, array : {$reduce : {input : "$array", initialValue : {$arrayElemAt : ["$array", 0]}, in : {$setIntersection : ["$$this", "$$value"]}}}}}
])
выход
> db.t67.aggregate([
... {$group : {_id : null, array : {$push : "$array"}}},
... {$project : {_id :0, array : {$reduce : {input : "$array", initialValue : {$arrayElemAt : ["$array", 0]}, in : {$setIntersection : ["$$this", "$$value"]}}}}}
... ])
{ "array" : [ { "userID" : 1, "name" : "name 1" }, { "userID" : 2, "name" : "name 2" }, { "userID" : 3, "name" : "name 3" } ] }
или $unwind
и $group
db.t67.aggregate([
// $match stages to filter 2 documents
{$unwind : "$array"},
{$group : {_id : "$array", count : {$sum : 1}}},
{$match : {count : {$gt : 1}}},
{$project : {count : 0}},
{$group : {_id : null, array : {$push : "$_id"}}},
{$project : {_id : 0}}
])
выход
{ "_id" : null, "array" : [ { "userID" : 3, "name" : "name 3" }, { "userID" : 2, "name" : "name 2" }, { "userID" : 1, "name" : "name 1" } ] }