1

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.