0

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 ?

3 Answers 3

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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)}});
})

1 Comment

Thanks for your answer. I'm already aware of doing this via Mongo Shell. I'm looking for something in MongoDB PHP, as its clearly mentioned in the question.
0

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);
    }
);

2 Comments

But aren't you going through all documents this way? "product_id": "1" exists as much as "product_id": 2 exists.
yes it goes thru all documents, the first condition is to ensure that product_id is present in the document.

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.