user8847697
user8847697

Reputation:

Concat int and string array fields which are in different arrays

{ 
   "no" : "2020921008981",  
   "date" : ISODate("2020-04-01T05:19:02.263+0000"), 
   "sale" : { 
   "soldItems" : [
       {
         "itemId" : "5b55ac7f0550de00210a3b24", 
         "qty" : NumberInt(1), 
       },
       {
         "itemId" : "5b55ac7f0550de00210a3b25", 
         "qty" : NumberInt(2), 
       }
     ],
  "items" : [
       {
         "_id" : ObjectId("5b55ac7f0550de00210a3b24"),
         unit :"KG"
       },
       {
         "_id" : ObjectId("5b55ac7f0550de00210a3b25"),
         unit :"ML"
       }

     ]
   }
 }

Desired output :

{
 "no" : "2020921008981",
 "sale" : {}
 "qtyList" : "1 KG \n 2 ML"
}

In order to build itemQtyList output field, two fields from different arrays (string and int) should be used. Couldn't find any reference for doing that. Any idea would be appreciated.

Upvotes: 2

Views: 94

Answers (1)

Ashh
Ashh

Reputation: 46481

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "itemQtyList": {
      "$reduce": {
        "input": { "$range": [0, { "$size": "$sale.soldItems" }] },
        "initialValue": "",
        "in": {
          "$concat": [
            "$$value",
            { "$cond": [{ "$eq": ["$$this", 0] }, "", " \n "] },
            { "$toString": {
              "$arrayElemAt": [
                "$sale.soldItems.qty",
                "$$this"
              ]
            }},
            " ",
            { "$arrayElemAt": ["$sale.items.unit", "$$this"] }
          ]
        }
      }
    }
  }}
])

MongoPlayground

Upvotes: 1

Related Questions