Skip to content

Instantly share code, notes, and snippets.

@MonksterFX
Created December 9, 2020 14:38
Show Gist options
  • Save MonksterFX/c06e8fdeaa577760a325424ed3a84bd6 to your computer and use it in GitHub Desktop.
Save MonksterFX/c06e8fdeaa577760a325424ed3a84bd6 to your computer and use it in GitHub Desktop.
Standart Flow For Better Control Of Subdocument Filtering
// MongoDB Playground
// To disable this template go to Settings | MongoDB | Use Default Template For Playground.
// Make sure you are connected to enable completions and to be able to run a playground.
// Use Ctrl+Space inside a snippet or a string literal to trigger completions.
// Select the database to use.
use('mongodbVSCodePlaygroundDB');
// The drop() command destroys all data from a collection.
// Make sure you run it against proper database and collection.
db.rights.drop();
// Insert a few documents into the sales collection.
db.rights.insertMany([
{
chat: 1,
messages: [
{ text: 'system', rights: ['A'] },
{ text: 'system', rights: ['B'] },
],
},
{
chat: 2,
messages: [
{ text: 'system', rights: ['A', 'B'] },
{ text: 'system', rights: ['A', 'C'] },
],
},
{
chat: 3,
messages: [
{ text: 'system', rights: ['A', 'B', 'C'] },
{ text: 'system', rights: [] },
],
},
{ chat: 4, messages: [{ text: 'system', rights: [] }] },
{ chat: 5, messages: [{ text: 'system' }] },
]);
db.rights.aggregate([
{
$unwind: {
path: '$messages',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
'messages.rights': {
$in: ['B'],
},
},
},
{
$group: {
_id: '$_id',
root: {
$mergeObjects: '$$ROOT',
},
messages: {
$push: '$messages',
},
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: ['$root', '$$ROOT'],
},
},
},
{
$unset: ['root'],
},
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment