2

How can we convert a numeric string to number in Mongodb?

Actual Problem: Collection: try Two Sample documents stored in try collection:

{
  _id: "1"
  testField: 150
}


{
  _id: "A"
  testField: 140
}

I want to filter out the _id field in the project phase for further processing in group phase. The query below is working fine but I need better solution for it like using type or any other method.

db.try.aggregate([{$match: {"_id":{$in:["1","2","3","4","5","6","7","8","9"]}}}, {$group:{"_id":0, total: {$sum:"$testField"}}}])
8
  • This query will give all _id db.try.find({"_id":{$type:2}}). As '_id' will be always string, it is not meaningful query. Can you provide more details please? Furthermore you can follow link docs.mongodb.org/manual/reference/operator/query/type Commented Apr 22, 2015 at 10:49
  • 2
    @Vishwas what's the benefit of this query? This will not differentiate between "1" and "A". Commented Apr 22, 2015 at 10:54
  • 1
    @CodeCore you want to find numeric ids which were saved as string. Right? Commented Apr 22, 2015 at 11:02
  • Also, you are using $in for 1-9. Do you have only 9 records(as _id is unique) ? Commented Apr 22, 2015 at 11:06
  • 1
    @CodeCore solution by Karthik will work for any number of digit. Commented Apr 22, 2015 at 11:27

2 Answers 2

2

You can use regex in this case:

db.try.aggregate([{$match: {"_id":
{$in:[/\d+/]}}}, 
{$group:{"_id":0, total: {$sum:"$testField"}}}])
Sign up to request clarification or add additional context in comments.

Comments

0

An alternative is to use MapReduce where in your map function you can check whether an _id contains a number:

Sample documents:

db.try.insert([
    {
      _id: "1",
      testField: 150
    },
    {
      _id: "2",
      testField: 150
    },
    {
      _id: "A",
      testField: 140
    },
    {
      _id: "B",
      testField: 140
    }
]);

MapReduce:

var map = function(){
    var numeric_id = !isNaN(this._id) ? "numeric" : "non_numeric";
    emit(numeric_id, this.testField); 
};

var reduce = function(key, values) {
    return Array.sum(values);
};

db.try.mapReduce(
    map,
    reduce,
    { out: "try_totals" }
);

Result:

db.try_totals.find()

/* 0 */
{
    "_id" : "non_numeric",
    "value" : 280
}

/* 1 */
{
    "_id" : "numeric",
    "value" : 300
}

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.