Concat int and string array fields which are in different arrays

半腔热情 提交于 2020-05-15 09:25:53

问题


{ 
   "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:


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



来源:https://stackoverflow.com/questions/61173858/concat-int-and-string-array-fields-which-are-in-different-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!