remove “\n” from values fields results in mongo db

99封情书 提交于 2019-12-24 08:09:36

问题


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!


回答1:


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.




回答2:


You can try below aggregation

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


来源:https://stackoverflow.com/questions/52427002/remove-n-from-values-fields-results-in-mongo-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!