Reputation: 55
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
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
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
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