Search code examples
mongodbaggregation-frameworkprojectaggregation

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


I would like to concat the array field values inside an array of objects into one string field. Heres the existing document format:

{ 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"), 
  "notes" : [
    {
        "_id" : ObjectId("5b55aabe0550de0021097bf0"),  
        "term" : "BLA BLA"
    }, 
    {
        "_id" : ObjectId("5b55aabe0550de0021097bf1"), 
        "term" : "BLA BLA BLA"
    }, 
    {
        "_id" : ObjectId("5b55aabf0550de0021097ed2"), 
        "term" : "BLA"
     }
  ], 
   "client" : "John Doe"
}

The required document format:

{ 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"),  
  "notes" : "BLA BLA \n BLA BLA BLA \n BLA",
  "client" : "John Doe"
}

The attempt with $project :

 { "$project": {    
      "notes": { 
            "$map": { 
                "input": "$notes", 
                "as": "u", 
                  "in": { 
                      "name": { "$concat" : [ "$$u.term", "\\n" ] } 
                  } 
             }
         }
     }
 }

but this returns this :

{ 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"),  
  "client" : "John Doe"
  "notes" : [
    {
        "name" : "BLA \n"
    }, 
    {
        "name" : "BLA BLA \n"
    }, 
    {
        "name" : "BLA BLA BLA \n"
    }
  ]
}

How to get it to the required format? Any idea would be appreciated!

Edit :

If we try to add array field values together, how can we do it it this way without grouping?

Existing format :

{
   "sale" : { 
       "bills" : [
        {
            "billNo" : "1234567890", 
            "billAmt" : NumberInt(1070), 
            "tax" : NumberInt(70) 
          }
       ]
    }, 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000")

}

Required :

{
 "no" : "123456789",  
 "date" : ISODate("2020-04-01T05:19:02.263+0000"),
 "total" : NumberInt(1140)
}

Solution

  • You can use $reduce to convert an array of strings into single string:

    db.collection.aggregate([
        {
            $addFields: {
                notes: {
                    $reduce: {
                        input: "$notes.term",
                        initialValue: "",
                        in: {
                            $cond: [ { "$eq": [ "$$value", "" ] }, "$$this", { $concat: [ "$$value", "\n", "$$this" ] } ]
                        }
                    }
                }
            }
        }
    ])
    

    Mongo Playground