本文介绍了Mongodb-如果有条件,聚合$ push的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试汇总一批文档.我要$ push的文档中有两个字段.但是,可以说它们是"_id"和"A"字段,如果"A"是$ gt 0,我只希望$ push"_id"和"A".

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.

我尝试了两种方法.

第一个.

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.

第二个.

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...

在其他情况下是否可以跳过$ push?

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

添加:

预期文件:

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

预期输出:

{
    "field":[
        {
            "A":"2",
            "_id":objectid(1)
        },
        {
            "A":"3",
            "_id":objectid(2)
        },
    ],
    "secondField":["One", "Two", "Three"]
}

推荐答案

这是我阅读@Veeram建议的帖子后对问题的回答

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

这篇关于Mongodb-如果有条件,聚合$ push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:49