Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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