【问题标题】:How to convert nested array of object values to comma separated string using MongoDB如何使用 MongoDB 将嵌套的对象值数组转换为逗号分隔的字符串
【发布时间】:2020-06-06 08:43:45
【问题描述】:

我的文档中有一些使用 MongoDb 的嵌套对象数组。我在下面解释我的文档。

{
  "Products" : [ 
        {
            "ID" : 0,
            "StoreCode" : "CMHB",
            "StoreName" : "CMR NPS",
            "StoreDescription" : "CMR NPS  International Store is a place where Parents can purchase all the school merchandise in one place at reasonable prices.",
            "StoreBranch" : "HRBR Layout",
            "AddressLine1" : "HRBR Layout",
            "AddressLine2" : "HRBR Layout",
            "Street" : "",
            "Landmark" : "",
            "Latitude" : "0",
            "Longitude" : "0",
            "City" : "Bengaluru",
            "State" : "Karnataka",
            "Country" : "India",
            "Pincode" : "560043",
            "StoreType" : "Online",
            "WarehouseCode" : "D0001",
            "Description" : "",
            "ProductName" : "Grade-12 Commerce EABM Book Kit",
            "ProductCode" : "VNTKEPCBM",
            "ProductType" : "S",
            "Brand" : "EP",
            "VendorCode" : "",
            "SKU" : "CMHBVNTKEPCBM",
            "CONSKU" : "",
            "BASESKU" : "",
            "PARENTSKU" : "",
            "SubProducts" : [],
            "CategoryId" : "",
            "CategoryName" : "Books/Kit",
            "AttributeSet" : "4000000",
            "Gender" : "",
            "BaseUnitPrice" : 0,
            "TaxPercentage" : 0,
            "HSNCode" : 4901,
            "BaseUnitOfMeasure" : "",
            "Weight" : 0,
            "TaxAmount" : 0,
            "MRP" : 0,
            "Weightage" : "",
            "DiscountPrice" : 0,
            "TotalOrderQuantity" : 1,
            "TotalProductPrice" : 0,
            "TotalProductDiscountPrice" : 0,
            "MinimumPrice" : 0,
            "CurrencyCode" : "INR",
            "MinimumBuyQty" : 1,
            "MaximumBuyQty" : 1,
            "TotalBaseUnitofMeasure" : "",
            "TotalWeight" : ""
        }
    ],
}

所以这是一个示例记录,我有一个产品数组,其中有一个键名SKU。我需要在逗号分隔的字符串中连接所有 SKU 值。让我在下面解释一下我现有的查询。

db.getCollection('orders').aggregate([
      {
          $match: {"Customer.StoreCode":"CMHB"}
      },
      {
          $group: {
              _id : "$Customer.CustomerMobile", 
              "data" : {
                  "$push": {
                     OrderNumber:"$OrderNumber",
                    OrderStatus:"$OrderStatus",
                    OrderType:"$OrderType",
                    CreatedAt:{ $dateToString: { format: "%Y-%m-%d", date: "$CreatedAt" } },
                    CustomerMobile: "$Customer.CustomerMobile",
                    CustomerLastName:"$Customer.CustomerLastName",
                    CustomerFirstName:"$Customer.CustomerFirstName",
                    StoreCode:"$Customer.StoreCode",
                    TransactionId:"$PaymentDetails.TransactionId",
                    PaymentStatus:"$PaymentDetails.PaymentStatus",
                    PaymentAmount:"$PaymentDetails.PaymentAmount",
                    ItemNos: { $cond: { if: { $isArray: "$Products" }, then: { $size: "$Products" }, else: "NA"} },
                    BillingAddressesLine1: "$Customer.BillingDetails.BillingAddressesLine1",
                    BillingAddressesLine2: "$Customer.BillingDetails.BillingAddressesLine2"
                  }
              }
          }
      }
]).toArray()

这里我需要再添加一个键i.e-SKU,它的值应该是产品数组中所有sku值的逗号分隔字符串,如e.g-sku1,sku2,sku3....

【问题讨论】:

    标签: arrays mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您需要添加这些更改:

    你的$group 舞台需要这个:

    SKU: { $push: "$Products.SKU"} // Since SKU is in Products array, final SKU will be array of arrays [[123,456], [789]]
    

    添加新阶段$addFields

    {
          $addFields: {
            SKU: {
              $substr: [
                {
                  "$reduce": {
                    "input": { "$reduce": { "input": "$SKU", "initialValue": [], "in": { "$setUnion": [ "$$value", "$$this" ] } } }, // Merge array of arrays to one array
                    "initialValue": "",
                    "in": { "$concat": [ "$$value", ",", "$$this" ] } // Concat array of strings to one string & remove first char from final string which is `,`
                  }
                },
                1,
               -1
             ]
           }
         }
      }
    

    测试: mongoplayground

    参考: aggregation

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2019-01-23
      • 2020-05-21
      • 2011-06-18
      • 2019-05-19
      相关资源
      最近更新 更多