Aicha Maghrebi
Aicha Maghrebi

Reputation: 63

remove "\n" from values fields results in mongo db

How can I remove "\n" from results of searching values in mongo db without remove it from the values of mongo db ? please I need your help!

Upvotes: 1

Views: 3525

Answers (2)

Ashh
Ashh

Reputation: 46481

You can try below aggregation

db.collection.aggregate([
  { "$project": {
    "textstr": {
      "$reduce": {
        "input": { "$split": ["$textstr", "\n"] },
        "initialValue": "",
        "in": { "$concat": ["$$this", " ", "$$value"] }
      }
    }
  }}
])

Upvotes: 1

mdewit
mdewit

Reputation: 2036

Example with 2 documents:

db.testcol.insert({
    textstr: "Hello World\nBye World\nHello World\n"
})
db.testcol.insert({
    textstr: "Testing\n123\nTesting\n"
})

db.testcol.find({}, {_id: 0, textstr: 1}).forEach(function(e, i) {
    e.textstr=e.textstr.replace(new RegExp('\n', 'g'), "");
    printjson(e);
});

Will output:

{
    "textstr" : "Hello WorldBye WorldHello World"
}
{
    "textstr" : "Testing123Testing"
}

Worth noting that if you want to replace the /n with another character, such as a space, you can do that by changing the second parameter of replace to a string of your choice.

Upvotes: 0

Related Questions