从MongoDB文档中的数组中有条件地选择字段

时间:2018-11-11 14:56:59

标签: mongodb mongodb-query aggregation-framework

我对mongodb比较陌生。我有一个像这样的文件:

docker-compose down -v

我希望将此文档转换为更简单的版本,以便将其下载为CSV格式。

{
    "_id" : ObjectId("5bcf50938847292ecbadc3c1"),
    "obsrvblKy" : "ABCDEFGHIJ",
    "obsrvblKnd" : "PRICE",
    "pblshrNm" : "BT",
    "pblshrSrc" : "BT",
    "dstrbtr" : "BT",
    "crtdOn" : ISODate("2018-10-23T12:47:15.544Z"),
    "qut" : [
            {
                    "qlfr" : "BID",
                    "vl" : 100,
                    "mrkTmstmp" : ISODate("2018-10-23T12:47:05.524Z"),
                    "mrkDt" : ISODate("2018-10-23T00:00:00Z")
            },
                            {
                    "qlfr" : "ASK",
                    "vl" : 101,
                    "mrkTmstmp" : ISODate("2018-10-23T12:47:05.524Z"),
                    "mrkDt" : ISODate("2018-10-23T00:00:00Z")
            },
                            {
                    "qlfr" : "MID",
                    "vl" : 100.50,
                    "mrkTmstmp" : ISODate("2018-10-23T12:47:05.524Z"),
                    "mrkDt" : ISODate("2018-10-23T00:00:00Z")
            }
    ],
    "mrkCurrncy" : "USD",
    "sttlmntDt" : "2018-10-30"        
}

有人可以指出我该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以在下面的3.6版本中进行汇总。

db.colname.aggregate([
{"$replaceRoot":{
  "newRoot":{
    "$reduce":{
      "input":"$qut",
      "initialValue":"$$ROOT",
      "in":{
        "$mergeObjects":[
          {"$arrayToObject":[[
            ["$$this.qlfr","$$this.vl"],
            [{"$concat":["$$this.qlfr","-","TimeStamp"]},"$$this.mrkTmstmp"]
          ]]},
          "$$value"
        ]
      }
    }
  }
}},
{"$project":{"crtdOn":0,"qut":0,"mrkCurrncy":0,"sttlmntDt":0}}
])