使用Aggregator函数查询MongoDB数组:实现预期产出?

fumotvh3  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(177)

对于我的问题,我有下面的样本数据库记录和输出需要开发的结果,如输出台中提到的。我对mongoDb非常陌生,但尝试$match$aggregator$projection来开发预期的结果。任何建议和帮助将不胜感激

{
    "_id": "act_8347100017075469",
    "firstName": "Akki",
    "lastName": "Dlast",
    "accountNumber": "12397124",
    "feature": {
      "feature-name1": {
        "baseCode": "bc1",
        "serviceCode": [
          //numb of elements & name of elements in servicesCodes are dynamic
          "SC1",
          "SC2",
          "SC3"
        ]
      },
      "feature-name2": {
        "baseCode": "bc2",
        "serviceCode": [
          //numb of elements & name of elements in servicesCodes are dynamic
          "SC21",
          "SC22"
        ]
      },
      "feature-name3": {
        "baseCode": "bc3",
        "serviceCode": [
          "SC41",
          "SC42",
          "SC43"
        ]
      }
    }
  }

输出

Account No  feature-name,  base-code,  svc-code
12397124,   feature-name1,  bc1,          SC1
12397124,   feature-name1,  bc1,          SC1 
12397124,   feature-name1,  bc1,          SC3
12397124,   feature-name2,  bc2,          SC21
12397124,   feature-name2   bc2,          SC21 
12397124,   feature-name3,  bc3,          SC41
12397124,   feature-name3   bc3,          SC42 
12397124,   feature-name3,  bc3,          SC43

尝试聚合管道(mongoplayground.net example):

db.collection.aggregate([
  {
    $match: {
      "feature.feature-name1.baseCode": {
        $exists: true
      }
    }
  },
  {
    $project: {
      accountNbr: 1,
      "feature": "feature-name1",
      "baseCode": "$feature.feature-name1.baseCode"
    }
  }
])

...但这只返回所需输出的一部分。

[
  {
    "_id": "act_8347100017075469",
    "baseCode": "bc1",
    "feature": "feature-name1"
  }
]
oknwwptz

oknwwptz1#

有个办法可以帮你

db.collection.aggregate([
  {
    "$set": {
      "feature": {
        "$objectToArray": "$feature"
      }
    }
  },
  {
    "$unwind": "$feature"
  },
  {
    "$unwind": "$feature.v.serviceCode"
  },
  {
    "$sort": {
      "accountNumber": 1,
      "feature.k": 1,
      "feature.v.baseCode": 1,
      "feature.v.serviceCode": 1
    }
  },
  {
    "$project": {
      "_id": 0,
      "Account No": "$accountNumber",
      "feature-name": "$feature.k",
      "base-code": "$feature.v.baseCode",
      "svc-code": "$feature.v.serviceCode"
    }
  }
])

mongoplayground.net上试试。

相关问题