Categories
Development MongoDB

addToSet with multiple condition in aggregation mongodb

I have document like this:

  {
    "_id" : ObjectId("5dc3c093c05bd833c4258e25"),
    "subscriber_id" : 4504,
    "user_country" : "India",
    "event" : "eventA"
  },
  {
    "_id" : ObjectId("5dc3c093c05bd833c4258e25"),
    "subscriber_id" : 4504,
    "user_country" : "India",
    "event" : "eventB"
  }

From below query I get:

db.collection.aggregate( 
   { 
      $project:{ 
         _id:1,
         user_country:1,
         subscriber_id:1,
         event:1
      }
   },
   { 
      $group:{ 
         "_id":{ 
            "subscriber_id":"$subscriber_id",
            "eventA":{ 
               $cond:{ 
                  "if":{ 
                     "$and":[ 
                        { 
                           "$eq":[ 
                              "$event",
                              "eventA"
                           ]
                        }
                     ]
                  },
                  then:1,
                  else:0
               }
            },
            "eventB":{ 
               $cond:{ 
                  "if":{ 
                     "$and":[ 
                        { 
                           "$eq":[ 
                              "$event",
                              "eventB"
                           ]
                        }
                     ]
                  },
                  then:1,
                  else:0
               }
            }
         }
      }
   },
   { 
      $group:{ 
         "_id":{ 
            "subscriber_id":"$_id.subscriber_id"
         },
         "event_details":{ 
            $push:{ 
               "eventA":"$_id.eventA",
               "eventB":"$_id.eventB"
            }
         }
      }
   }
);

Output:

{ 
   "_id":{ 
      "subscriber_id":4504
   },
   "event_details":[ 
      { 
         "eventA":0,
         "eventB":0
      },
      { 
         "eventA":1,
         "eventB":0
      },
      { 
         "eventA":0,
         "eventB":1
      }
   ]
}

Now I want for each row whatever event has 1 value should be push into array so my next step output should be like this

{ 
   "_id":{ 
      "subscriber_id":4504
   },
   "event_details":[ 
      "eventA",
      "eventB"
   ]
}

Here eventA and eventB both has value 1, so both will pushed to array.

Leave an answer

Your email address will not be published. Required fields are marked *