praveen.menezes
praveen.menezes

Reputation: 55

Change datatype from string to integer in MongoDB PHP

I have a set of documents where some of product_id are stored in string

[
  {
    "_id": ObjectId("foobar1"),
    "product_id": "1"
  },
  {
    "_id": ObjectId("foobar2"),
    "product_id": 2
  }
]

Is there any way to convert product_id to integer for all the documents using MongoDB PHP ?

Upvotes: 0

Views: 821

Answers (3)

Alex P.
Alex P.

Reputation: 3171

You can also search for the specific type. Check out the documentation of $type. Strings are $type: 2

db.collection.find({
    product_id: {
        $type: 2
    }
}).forEach(function(doc) {
    doc.product_id = new NumberInt(doc.product_id);
    db.product.save(doc);
});

Upvotes: 2

Clement Amarnath
Clement Amarnath

Reputation: 5466

Better and simpler approach would be doing it in the MongoShell itself, the below javascript function will does the job of converting all product_id from String to integer.

This will work if all the product_id string can be converted to an integer, say the possible values of product_id can be "1", "34343", "23", ....

db.collection.find({product_id: {$exists : true}}).forEach(
    function(obj) { 
        obj.product_id = new NumberInt( obj.product_id );
        db.collection.save(obj);
    }
);

Upvotes: 0

Smita Ahinave
Smita Ahinave

Reputation: 1888

this may help you...

db.collection.find().forEach(function(product) {
    product.product_id= new NumberInt(product.product_id);
    db.collection.save(product);
});

OR using UPDATE

db.collection.find().forEach(function(data) {
    db.collection.update({_id:data._id},{$set:{product_id:parseInt(data.product_id)}});
})

Upvotes: 0

Related Questions