-
Type: Improvement
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
Query Optimization
$facet is not allowed inside of another $facet. However, if a $facet has in its pipelines a stage that operates over a view, and that view is defined using $facet, we cannot detect this invalid syntax.
db.people.insertMany([{_id: 0, name: "Jan", friends: ["Sara", "Martin"], hobbies: "tennis"}, {_id: 1, name: "Martin", friends: ["Ken", "Andrew"], hobbies: "cycling"}, {_id: 2, name: "Sara", friends: ["Ken", "Jenniffer"], hobbies: "travel"}, {_id: 3, name: "Ken", friends: ["Sara", "Andrew"], hobbies: "cycling"}]); db.createView("peopleViewFacet", "people", [{$facet: {"peopleWithFriends": [{$project: {name:1, friends:1}}]}}, {$unwind: "$peopleWithFriends"}, {$project: {"_id": "$peopleWithFriends._id", "name": "$peopleWithFriends.name", "friends": "$peopleWithFriends.friends"}}]); let graphLookupStage = {$graphLookup: { from: "peopleViewFacet", startWith: "$friends", connectFromField: "friends", connectToField: "name", maxDepth: 3, as: "friendsCircle"} }; let projectStage = {$project: {"name": 1, "friends": 1, "socialCircle" : "$friendsCircle.name"}}; // The following aggregation contains a $facet inside a $facet and is expected to give an error, but it works. db.people.aggregate([ { "$facet" : {"result" : [ graphLookupStage, projectStage]}}]); // Result { "result" : [ { "_id" : 0, "name" : "Jan", "friends" : [ "Sara", "Martin" ], "socialCircle" : [ "Martin", "Sara", "Ken" ] }, ... }