US-1234
US-1234

Reputation: 1529

Matching field by omitting spaces - MongoDB

I'm trying to find the mongo document by matching the "Tel" field value,

{ 
    "_id" : ObjectId("54f047aa5b9e5c7c13000000"),    
    "data" : [
        {
            "Id" : "1", 
            "Country" : "India", 
            "Timezone" : "Europe/Paris", 
            **"Tel" : "03 20 14 97 70",** 
            "Prenom" : "ddd", 
            "Email" : "[email protected]", 
            "City" : "Chennai", 
            "date" : "", 
            "active" : "true"
        }
    ]
}

how to fetch the above document from mongo collection using the below find method without space in "Tel" field,

>db.test.find({"data.Tel":"0320149770"})

Please can anyone help me !!!

Upvotes: 1

Views: 1012

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

If this is what you really want to do on a regular basis then you are best off adding another field to the document that has the string present without any spaces.

The reason why is though there are functions you can perform to do the search, none of the methods are able to use an index to match the document, so this means scanning everything in the collection in order to find a match.

You can do this with JavaScript evaluation in a $where clause:

db.test.find(function() { 
    return this.data.some(function(el) {
        el.Tel.replace(/ /g,"") == "0320149770"
    });
});

But don't do that because it's really bad. you are better off just updating all the data instead:

db.test.find().forEach(function(doc) {
    doc.data = doc.data.map(function(el) {
        el.TelNum = el.Tel.replace(/ /g,"");
    })
    db.test.update({ "_id": doc._id },{ "$set": { "data": doc.data } });
})

Or something along those lines to have a field without spaces all ready to search on directly.

Upvotes: 3

Related Questions