Mongodb - aggregation $push if conditional
Asked Answered
G

4

46

I am trying to aggregate a batch of documents. There are two fields in the documents I would like to $push. However, lets say they are "_id" and "A" fields, I only want $push "_id" and "A" if "A" is $gt 0.

I tried two approaches.

First one.

db.collection.aggregate([{
"$group":{
    "field": {
        "$push": {
            "$cond":[
                {"$gt":["$A", 0]},
                {"id": "$_id", "A":"$A"},
                null
            ]
        }
    },
    "secondField":{"$push":"$B"}
}])

But this will push a null value to "field" and I don't want it.

Second one.

db.collection.aggregate([{
"$group":
    "field": {
        "$cond":[
            {"$gt",["$A", 0]},
            {"$push": {"id":"$_id", "A":"$A"}},
            null
        ]
    },
    "secondField":{"$push":"$B"}
}])

The second one simply doesn't work...

Is there a way to skip the $push in else case?

ADDED:

Expected documents:

{
    "_id":objectid(1),
    "A":2,
    "B":"One"
},
{
    "_id":objectid(2),
    "A":3,
    "B":"Two"
},
{
    "_id":objectid(3),
    "B":"Three"
}

Expected Output:

{
    "field":[
        {
            "A":"2",
            "_id":objectid(1)
        },
        {
            "A":"3",
            "_id":objectid(2)
        },
    ],
    "secondField":["One", "Two", "Three"]
}
Gagnon answered 6/4, 2018 at 6:51 Comment(2)
I think your approach cannot work docs.mongodb.com/manual/reference/operator/aggregation/push > $push is only available in the $group stage.Epochmaking
@Epochmaking I corrected my question.Gagnon
G
24

This is my answer to the question after reading the post suggested by @Veeram

db.collection.aggregate([{
"$group":{
    "field": {
        "$push": {
            "$cond":[
                {"$gt":["$A", 0]},
                {"id": "$_id", "A":"$A"},
                null
            ]
        }
    },
    "secondField":{"$push":"$B"}
},
{
    "$project": {
        "A":{"$setDifference":["$A", [null]]},
        "B":"$B"
    }
}])
Gagnon answered 6/4, 2018 at 15:27 Comment(2)
There is a typo in setDifference here.Remnant
Hi there, found this while googling, how would you convert the setDifference arguments to the mgo library? Which type?Dues
A
53

You can use "$$REMOVE":

  • This system variable was added in version 3.6 (mongodb docs)
db.collection.aggregate([{
   $group:{
       field: {
          $push: {
              $cond:[
                { $gt: ["$A", 0] },
                { id: "$_id", A:"$A" },
                "$$REMOVE"
            ]
          }
        },
        secondField:{ $push: "$B" }
    }
])

In this way you don't have to filter nulls.

Amasa answered 6/2, 2020 at 13:49 Comment(2)
$$REMOVE is a system variable, not operatorSequela
Thanks, this approach save 1 additional stage of $project, just to remove nullHarney
G
24

This is my answer to the question after reading the post suggested by @Veeram

db.collection.aggregate([{
"$group":{
    "field": {
        "$push": {
            "$cond":[
                {"$gt":["$A", 0]},
                {"id": "$_id", "A":"$A"},
                null
            ]
        }
    },
    "secondField":{"$push":"$B"}
},
{
    "$project": {
        "A":{"$setDifference":["$A", [null]]},
        "B":"$B"
    }
}])
Gagnon answered 6/4, 2018 at 15:27 Comment(2)
There is a typo in setDifference here.Remnant
Hi there, found this while googling, how would you convert the setDifference arguments to the mgo library? Which type?Dues
G
9

One more option is to use $filter operator:

db.collection.aggregate([
{ 
    $group : {
        _id: null,
        field: { $push: { id: "$_id", A : "$A"}},
        secondField:{ $push: "$B" }
    }
},
{
    $project: {
        field: {
            $filter: {
                input: "$field",
                as: "item",
                cond: { $gt: [ "$$item.A", 0 ] }
            }
        },
        secondField: "$secondField"
    }       
}])

On first step you combine your array and filter them on second step

Goosestep answered 6/4, 2018 at 14:55 Comment(0)
K
1
 $group: {
        _id: '$_id',
        tasks: {
          $addToSet: {
            $cond: {
              if: {
                $eq: [
                  {
                    $ifNull: ['$tasks.id', ''],
                  },
                  '',
                ],
              },
              then: '$$REMOVE',
              else: {
                id: '$tasks.id',
                description: '$tasks.description',
                assignee: {
                  $cond: {
                    if: {
                      $eq: [
                        {
                          $ifNull: ['$tasks.assignee._id', ''],
                        },
                        '',
                      ],
                    },
                    then: undefined,
                    else: {
                      id: '$tasks.assignee._id',
                      name: '$tasks.assignee.name',
                      thumbnail: '$tasks.assignee.thumbnail',
                      status: '$tasks.assignee.status',
                    },
                  },
                },
              },
            },
          },
        },
     }
Kulda answered 24/8, 2022 at 17:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.