skip to Main Content

I have the following collection

{
  "_id": "12345",
  "Products": [
    "Product1",
    "Product2"
  ],
  "State": "active",
}

And would like to project it similar to the output below

_id: "12345"
Products: "Product1, product2"

I tried this but im not getting the desired output of a comman seperated concatenated string

{
  _id: 1,
  Products: { 
      $reduce: { 
          input: "$Products", 
          initialValue:"0" ,
          in: {concat:  ["$$value", "$$this"] } 
      }
  }
}

2

Answers


  1. You can use $reduce and $concat to concatenate the values into one string. The $cond is necessary to determine if a comma is required between the values or not.

    db.collection.aggregate([
      {
        $project: {
          "_id": 1,
          "Products": {
            $reduce: {
              input: "$Products",
              initialValue: "",
              in: {
                $concat: [
                  "$$value",
                  {
                    $cond: [
                      {
                        $eq: [
                          "$$value",
                          ""
                        ]
                      },
                      "",
                      ","
                    ]
                  },
                  "$$this"
                ]
              }
            }
          }
        }
      }
    ])
    

    See HERE for a working example.

    Login or Signup to reply.
  2. This aggregation query gives the desired result:

    db.test.aggregate([{
        $project: {
            Products: {
                $ltrim: {
                    input: {
                        $reduce: {
                            input: "$Products",
                            initialValue: "",
                            in: {
                                $concat: [ "$$value", ", ", "$$this" ]
                            }
                        }
                    },
                    chars: ", "
                }
            }
        }
    }])
    

    The $project is used to transform the Products array of strings into a single concatenated string, using the $reduce array operator.

    Note the usage of the $ltrim operator to remove the addition comma from the concatenated string, to give the following result:

    [ 
      { 
        _id: '12345', 
         Products: 'Product1, Product2' 
      } 
    ]
    

    The projection of _id field is not explicitly required, it is by default projected.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search