Sumon
Sumon

Reputation: 299

MongoDB aggregation skip null value key

I am trying to remove duplicate value from array which I am able to successfully achieve with below query however having difficulties skip key where values is null. I am using following code

db.mobile_data.aggregate([{$unwind: '$All_Participants'}, 
{$group: {_id:'$_id',All_Participants: {$addToSet: '$All_Participants'}, 
  Chat_group: {$first: '$Chat_group'}, Message_id: {$first: '$Message_id'} }}]);

my output result as follow

{ 
    "_id" : ObjectId("5856b1e39a47e6d13dab370b"), 
    "All_Participants" : [
        "user1", 
        "user4"
    ], 
    "Chat_group" : 67.0, 
    "Message_id" : Null
}

How can ignore Message_id if value is null? Expected output should be

{ 
    "_id" : ObjectId("5856b1e39a47e6d13dab370b"), 
    "All_Participants" : [
        "user1", 
        "user4"
    ], 
    "Chat_group" : 67.0
}

Upvotes: 1

Views: 3134

Answers (2)

Mandeep Singh
Mandeep Singh

Reputation: 365

Unfortunately, there is no way to remove 'null' fields during $group stage. We would need to add an additional $project stage after the $group stage to remove the null fields:

db.mobile_data.aggregate([
{$unwind: '$All_Participants'}, 
{$group: {_id:'$_id',All_Participants: {$addToSet: '$All_Participants'}, 
  Chat_group: {$max: '$Chat_group'}, Message_id: {$first: '$Message_id'} }},

{$project: {'All_Participants': 1, 'Chat_group': 1, 'Message_id': {
            $cond: {
               if: { $ifNull: [ "$Message_id", true ] },
               then: "$$REMOVE",
               else: "$Message_id"
            }}}}]);

If any other attributes (like 'Chat_group') can be null, then again a similar conditional projection would be required for it. Also note that I have used $max to group 'Chat_group' instead of $first so that it doesn't consider null values but it could lead to degraded performance.

Upvotes: 1

Riya Saxena
Riya Saxena

Reputation: 99

While unwinding 'All_Participants' you can use -> preserveNullAndEmptyArrays which will not unwind the null field if set to false. You can refer this link-> https://docs.mongodb.com/v3.2/reference/operator/aggregation/unwind/

Upvotes: 0

Related Questions