2
{ 
   "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.

1
  • a possible soultion: This kind of operation could easily be achieved in the programming language (javascript, java etc.) you are using mongodb with. Are the array lengths of purchaseItems and items same and position values are in sync? Commented Apr 12, 2020 at 15:47

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Im still getting the null value but can't figure out where went wrong..
@dineshalwis I have given you the link as well. kindly verify
please refer this question. stackoverflow.com/questions/61231005/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.