Aggregation $match

How write stage $match {} (all documents of collection )else user: ‘an email’ by condition? somewhat like: if (isAdmin==true) {$match:{}} else { $match:{user:‘an email’}
it is 1st stage of aggregation query, result for next stage all docs or docs match only belong / created that user.
isAdmin – var boolean outside of aggregation

Please provide sample documents and the expected result.

It is not clear if isAdmin is a field of the documents from your collection or a variable in your programming language.

thanks for answer,
[
{
“_id”: {
“$oid”: “630423495c8abda60dad5b47”
},
“title”: “e”,
“description”: “e”,
“user”: “atak@mail.org
},
{
“_id”: {
“$oid”: “630423615c8abda60dad5b70”
},
“title”: “eee”,
“description”: “eee”,
“user”: “mel@mail.org
},
{
“_id”: {
“$oid”: “630423ef5c8abda60daea1d3”
},
“title”: "Moncton ",
“description”: “Moncton’s Modality Shift”,
“user”: “alex@mail.org
},
{
“_id”: {
“$oid”: “630423ef5c8abda60daea1d5”
},
“title”: “New town”,
“description”: “Founded in 2021, Downtown town is the new hotness”,
“user”: “adam@mail.org
},
{
“_id”: {
“$oid”: “630423ef5c8abda60daea1d7”
},
“title”: “Market: Johner Fest 2022”,
“description”: “vv”,
“user”: “aby@mail.org
}
]

isAdmin – var boolean outside of aggregation

it is 1st stage of aggregation query, result for next stage all docs or docs match only belong / created that user. isAdmin – var boolean outside of aggregation

if ( isAdmin ) {
  match_stage = { "$match" : {} }
}
else {
  match_stage = { "$match" : { "user" : email } }
}

pipeline = [ match_stage , /* other stages */ ]

thanks, I’m sorry for stupid question, what is syntax to add that into like: db.collectionName.aggregate()? So, I’ve used to just syntax db.collectionName.aggregate([
{$match:…},
{$project:…},
{$group:…}

])

An aggregation pipeline is simply an array of JSON object. Each object being a stage. You can manipulate your pipeline with any logic and array operation you wish.

For example, by default, all documents are matched so having

match_stage = { "$match" : { } }

is useless and might even be detrimental to performances.

So alternatively you could do:

pipeline = [ ]

if ( ! isAdmin ) {
  pipeline.push( { "$match" : { "user" : email } } )
}

pipeline.push( { "$group" : { "_id" : null , count : { "$sum" : 1 } } } )

db.collectionName.aggregate( pipeline ) ;
3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.