Created
November 3, 2017 14:21
-
-
Save cthurston/7aead8229e10caa0be175babf7e8ddf1 to your computer and use it in GitHub Desktop.
MongoDb combine $facet results into a single result set.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
db.getCollection('list').aggregate([ | |
{ | |
$facet: { | |
"events":[{ | |
$match: { | |
'type': 'Event' | |
} | |
}], | |
"tasks": [{ | |
$match: { | |
'type': 'Task' | |
} | |
}] | |
} | |
}, | |
{$project: {activity:{$setUnion:['$events','$tasks']}}}, | |
{$unwind: '$activity'}, | |
{$replaceRoot: { newRoot: "$activity" }} | |
]); |
How would you apply skip and limit on the combined results?
How would you apply skip and limit on the combined results?
The scenario is not contrived. Salesforce has an activity type from which they extend to create events and tasks. However, often times you want to display all activity on a particular record, sorted correctly by some criteria. If you don't do it in the query using facet and setUnion you end up having to do extra logic on your server or in your client.
The documentation states that $setUnion
removes duplicates. How does that affect the final output if the output from both $facet stages contains fields with identical names?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was very useful, thank you!