Mongodb - aggregation $push if conditional

天涯浪子 提交于 2020-01-10 23:45:24

问题


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"]
}

回答1:


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"
    }
}])



回答2:


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



来源:https://stackoverflow.com/questions/49687020/mongodb-aggregation-push-if-conditional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!