crunk1
crunk1

Reputation: 2818

Extract $graphLookup matches into documents

For context, I'm using MongoDB 3.6.4 and I'm trying to build a hierarchical schema for ACL permissions, but I'll boil the problem down and save the details.

Say I have a simple collection C, where parents is a list of references to other documents in C:

{
  _id: ObjectId
  parents: Array(ObjectId)
}

If I do an aggregation like:

[
  {
    $match: {_id: ObjectId("f00...")}
  },
  {
    $graphLookup: {
      from: "C",
      startWith: "$parents",
      connectFromField: "parents",
      connectToField: "_id",
      as: "graph"
    }
  }
]

I get back data like:

{
  "_id": ObjectId("f00..."),
  "parents": [ObjectId("f01..."), ObjectId("f02..."), ...],
  "graph": [<doc1>, <doc2>, <doc3>, ...]
}

Is there a way to split the graph items out into documents? e.g. from the previous output example:

{
  "_id": ObjectId("f00..."),
  "parents": [ObjectId("f01..."), ObjectId("f02..."), ...]
}
<doc1>
<doc2>
<doc3>

Upvotes: 0

Views: 407

Answers (1)

s7vr
s7vr

Reputation: 75934

You can try adding below stages to query.

[
  {"$project":{"data":{"$concatArrays":[["$$ROOT"],"$graph"]}}},
  {"$unwind":"$data"},
  {"$project":{"data.graph":0}},
  {"$replaceRoot":{"newRoot":"$data"}}
]

Upvotes: 1

Related Questions