Search code examples
mongodbtype-conversionaggregatestring-concatenation

Concat int array field inside an array of object into one string field in mongodb aggregate


I would like to concat int array field values inside an array of objects into one string field after dividing them (by 10).

Heres the existing document format:

{ 
  "no" : "2020921008981",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"), 
  "sale" : { 
   "soldItems" : [
       {
         "itemRefId" : "5b55ac7f0550de00210a3b24", 
         "soldPrice" : NumberInt(800), 
       },
       {
         "itemRefId" : "5b55ac7f0550de00210a3b25", 
         "soldPrice" : NumberInt(1000), 
       }
     ] 
   }
 }

Expected result :

{ 
  "no" : "2020921008981",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"),  
  "priceList" : "8.0 \n 10.0"
}

The attempt with $reduce :

 priceList: {
            $reduce: {
                input: "$sale.soldItems.soldPrice",
                initialValue: "",
                in: {
                    $cond: [ { "$eq": [ { $toString: { $divide: [ "$$value", 10 ] } }, "" ] }, "$$this", { $concat: [ { $toString: { $divide: [ "$$value", 10 ] } }, "\n", "$$this" ] } ]
                }
            }
        }

But end up getting "errmsg" : "$divide only supports numeric types, not string and double" error. Any idea would be appreciated.


Solution

  • db.case.aggregate([
        {
            $set: {
                priceList: {
                    $reduce: {
                        input: {
                            $map: {
                                input: "$sale.soldItems.soldPrice",
                                in: { $toString: { $divide: ["$$this", 10] } }
                            }
                        },
                        initialValue: "",
                        in: { $concat: ["$$value", "$$this", " \n "] }
                    }
                }
            }
        },
        {
            $project: {
                _id: 0,
                no: 1,
                date: 1,
                priceList: 1
            }
        }
    ])