Reputation: 1228
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
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:
Upvotes: 2