How can I concatenate an array of integer in MongoDB aggregation method?

MongoDBDatabaseBig Data Analytics

To concatenate, use $concat in MongoDB aggregate(). Let us first create a collection with documents −

> db.demo377.insertOne({"ListOfIds":[1001,1002,1003,1004,1005,1006,1007]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a73462ae06a1609a00b0e")
}

Display all documents from a collection with the help of find() method −

> db.demo377.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e5a73462ae06a1609a00b0e"),
   "ListOfIds" : [
      1001,
      1002,
      1003,
      1004,
      1005,
      1006,
      1007
   ]
}

Following is the query to concatenate an array of integer in aggregation −

> db.demo377.aggregate([
...    { "$project": {
...       "ListOfIds": {
...          "$let": {
...             "vars": {
...                "key": {
...                   "$reduce": {
...                      "input": "$ListOfIds",
...                      "initialValue": "",
...                      "in": { "$concat": ["$$value", "++", { "$toLower": "$$this" }] }
...                   }
...                }
...             },
...             "in": { "$substrCP": ["$$key", 2, { "$strLenCP": "$$key" }] }
...          }
...       }
...    }}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e5a73462ae06a1609a00b0e"), "ListOfIds" : "1001++1002++1003++1004++1005++1006++1007" }
raja
Published on 02-Apr-2020 13:20:28
Advertisements