Reputation: 13
I inserted some data in a database collection named Orders. And I have a field named numberofh
.
But all fields in my collection are string types. I am connected to the mongo db shell on the server and I want to delete all orders where numberofh
is less then 5.
db.orders.remove({numberofh:{$lt:20}})
does not work because numberofh
is a string so $lt
won't work.
Can I do this some other way such as sdb.orders.remove({parseInt(numberofh}:{$lt:20})
?
Upvotes: 1
Views: 437
Reputation: 19474
You cannot compare strings with numbers in mongoDB. You have to first insert a new field, that is a numerical representation of numberofh
. And you have to do the conversion client-side. There is no possibility, to create a field in dependency of the value of another field.
db.orders.find( {} ).forEach( function (x) {
x.numberofh_n = parseInt( x.numberofh, 10 );
db.orders.save( x );
});
After that you can remove the records by the new field:
db.orders.remove( { numberofh_n: { $lt:20 } } )
Upvotes: 1
Reputation: 47976
I think you'll need to iterate over each of the documents and convert each value as the cursor reaches it:
db.orders.find().forEach( function( doc ) {
// Extract the relevant value and convert to an int
var numberofh_int = parseInt( doc[ "numberofh" ], 10 );
// Perform conditionals on the value
if ( numberofh_int < 20 ){ // $lt:20
// Remove the document if it answers to the conditions
db.orders.remove( doc );
}
} );
Upvotes: 1