0

How to extract the only number from string which starts with number in MongoDB

I want to extract the number from a string which starts with the number.

I have a collection which contains document like

  {
    "address" :"1103 wood crest"
  },
  {
    "address": "223 NW 28TH ST"
  },
  {
    "address": "NW 28TH ST"
  },
  {
    "address": "28TH ST ava"
   }

I want to write aggregation query, which gives result in below format: below:

{
  "number": "1103",
  "address" :"wood crest"
},
{
  "number": "223",
  "address": "223 NW 28TH ST"
},
{
  "number": "",
  "address": "NW 28TH ST"
},
{
   "number": "",
   "address": "28TH ST ava"
 }

1 Answer 1

1

Well, you can't do this with the aggregation framework. Your best bet here is mapReduce

db.coll.mapReduce(
    function() { 
        var fields = {}; 
        fields["number"] = parseInt(this.address.match(/^\d+?\s+/)) || "";
        fields["address"] =  this.address; 
        emit(this._id, fields); 
    }, 
    function(key, value) {}, 
    { "out": { "inline": 1 } }
)

which returns something like this:

{
        "results" : [
                {
                        "_id" : ObjectId("57691c0206c5c92152979d3e"),
                        "value" : {
                                "number" : 1103,
                                "address" : "1103 wood crest"
                        }
                },
                {
                        "_id" : ObjectId("57691c0206c5c92152979d3f"),
                        "value" : {
                                "number" : 223,
                                "address" : "223 NW 28TH ST"
                        }
                },
                {
                        "_id" : ObjectId("57691c0206c5c92152979d40"),
                        "value" : {
                                "number" : "",
                                "address" : "NW 28TH ST"
                        }
                },
                {
                        "_id" : ObjectId("57691c0206c5c92152979d41"),
                        "value" : {
                                "number" : "",
                                "address" : "28TH ST ava"
                        }
                }
        ],
        "timeMillis" : 25,
        "counts" : {
                "input" : 4,
                "emit" : 4,
                "reduce" : 0,
                "output" : 4
        },
        "ok" : 1
}
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.