Concat int和字符串数组字段位于不同的数组中 [英] Concat int and string array fields which are in different arrays

查看:84
本文介绍了Concat int和字符串数组字段位于不同的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

     ]
   }
 }

所需的输出:

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

为了构建itemQtyList输出字段,应使用来自不同数组的两个字段(字符串和整数).找不到执行此操作的任何参考.任何想法将不胜感激.

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.

推荐答案

您可以在下面的聚合中使用

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

这篇关于Concat int和字符串数组字段位于不同的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆