如果您使用的是 mongo 3.4+,您可以这样做$graphLookup
,它是对自我集合进行分层连接
db.frnds.aggregate([
{$match : {'name': 'A'}},
{
$graphLookup: {
from: "frnds",
startWith: "$name",
connectFromField: "name",
connectToField: "friends",
as: "friends"
}
},
{$addFields : { friends : {$setUnion : [{$filter : {input : "$friends.name", as : "friend" , cond : {$ne : ["$name", "$$friend"]}}}] }}}
])
收藏
> db.frnds.find()
{ "_id" : ObjectId("5a7e694580aae386f73cf0f5"), "name" : "A", "friends" : [ "B", "C" ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f6"), "name" : "B", "friends" : [ "A" ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f7"), "name" : "C", "friends" : [ "A" ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f8"), "name" : "D", "friends" : [ ] }
{ "_id" : ObjectId("5a7e694580aae386f73cf0f9"), "name" : "E", "friends" : [ "C" ] }
结果
{ "_id" : ObjectId("5a7e694580aae386f73cf0f5"), "name" : "A", "friends" : [ "B", "C", "E" ] }