在MongoDB管道中反对组id



我有一个返回这样输出的MongoDB聚合管道:

 [
    {
        "id": {
            "isPaid": false,
            "state": "approved",
            "updatedAt": "2018-06-27"
        },
        "state": "approved",
        "isPaid": false,
        "updatedAt": "2018-06-27",
        "totalCount": 1,
        "totalValue": 658.4332
    },
    {
        "id": {
            "isPaid": false,
            "state": "canceled",
            "updatedAt": "2018-05-30"
        },
        "state": "canceled",
        "isPaid": false,
        "updatedAt": "2018-05-30",
        "totalCount": 1,
        "totalValue": 1735.7175
    },
]

对于利用它的系统,我需要id以字符串形式可用。

所以我想知道,使用聚合管道阶段,是否会有一种优雅而通用的方式来将对象值连接/序列化为字符串:


"id": {"isPaid": false, "state": "approved", "updatedAt": "2018-06-27"}像这样:
"id": "0.approved.2018-06-27"

您可以使用$concat

db.t55.aggregate([
    {$addFields : {
        id : {$concat : [{$cond :["$isPaid", "1","0"]}, ".", "$state", "." ,"$updatedAt"]}
    }}
])

使用$toString(如果不是真的/假)

db.t55.aggregate([
    {$addFields : {
        id : {$concat : [{$toString :{$indexOfArray : [[false,true], "$isPaid"]}}, ".", "$state", "." ,"$updatedAt"]}
    }}
])

输出

{ "_id" : ObjectId("5c3e794b21526e3ff4bf4ca2"), "id" : "0.approved.2018-06-27", "state" : "approved", "isPaid" : false, "updatedAt" : "2018-06-27", "totalCount" : 1, "totalValue" : 658.4332 }
{ "_id" : ObjectId("5c3e794b21526e3ff4bf4ca3"), "id" : "0.canceled.2018-05-30", "state" : "canceled", "isPaid" : false, "updatedAt" : "2018-05-30", "totalCount" : 1, "totalValue" : 1735.7175 }

最新更新