Dilee
Dilee

Reputation: 276

Deleting a document from a mongodb collection

I have a collection called customers and it contains documents. I have written a function to delete a document using the field and its value which takes as arguments. But it doesn't remove any customer as expected. Can anybody show me where I have gone wrong?

function (fieldName, value) {
  db.customers.remove({x : y});
}

I called the function from the mongo terminal as below.

db.loadServerScripts();
removeDocument("firstName", "Sam");

Thanks

Upvotes: 2

Views: 1878

Answers (2)

Amanda
Amanda

Reputation: 68

db.collection.remove is deprecated so use deleteOne or deleteMany(For deleting multiple documents)

Upvotes: 1

chridam
chridam

Reputation: 103305

Rewrite your function so that the arguments become part of the query object. You can do this using either computed property or bracket notation.

Using computed property:

function removeDocument(fieldName, value) {
    db.customers.remove({[fieldName]: value});
}

Using bracket notation

function removeDocument(fieldName, value) {
    var query = {};
    query[fieldName] = value;
    db.customers.remove(query);
}

Upvotes: 2

Related Questions