DD DD
DD DD

Reputation: 1228

How to use concat with mongoose aggregate using $set

For example, I have a document as below.

{
   "test": "success"
}

And I want to add extra string value after "success".

{
   "test": "successfail"
}

Therefore I tried some aggregate using mongoose.

const Users = require("./userSchema")

Users.aggregate([
  {},
  [{ $set: { test: { $concat: [ "$test", "fail" ] } } }],
])

But this didn't work at all.
Could you recommend some solution for this? Thank you so much for reading this.

Upvotes: 1

Views: 163

Answers (1)

krishna Prasad
krishna Prasad

Reputation: 3812

To Concatenates string in the existing fields of a collection, you should use $project stage pipeline with $concat operator as below not the $set in the pipeline stage:

Users.aggregate([ { $project: { test: { $concat: [ "$test", "", "fail" ] } } } ])

For more details check the below queries with output also:

> db.st1.find()
{ "_id" : ObjectId("5dffa38b4a36d14455f50158"), "test" : "success" }
> db.st1.aggregate([{$project: {test: {$concat: ["$test", "fail" ]  }  }  }])
{ "_id" : ObjectId("5dffa38b4a36d14455f50158"), "test" : "successfail" }
>
> db.st1.aggregate([{$project: {test: {$concat: ["$test", "-", "fail" ]  }  }  }])
{ "_id" : ObjectId("5dffa38b4a36d14455f50158"), "test" : "success-fail" }
> 
> db.st1.aggregate([{$project: {test: {$concat: ["$test", "", "fail" ]  }  }  }])
{ "_id" : ObjectId("5dffa38b4a36d14455f50158"), "test" : "successfail" }

For references visit the official documentation of MongoDB:

  1. https://docs.mongodb.com/manual/reference/operator/aggregation/concat/#concat-aggregation

Upvotes: 2

Related Questions