Question

I'm new to MongoDB, so I'm aware this is a really simple question, but I've looked everywhere and I can't find an answer? Basically I'm trying to find all records within a collection that contain the word "delete" and delete them. To get the records, I'm using

 db.collection.distinct("delete")

(correct me if I'm wrong there). But how would I go about actually deleting those? I've tried creating a variable out of that (i.e.

 var query = db.collection.distinct("delete")

) and then executing

db.collection.remove(query)

but the records are still there? Any help would be great!

Was it helpful?

Solution

Assuming that you're trying to delete all docs that contain a delete field:

db.collection.remove({delete: {$exists: true}});

OTHER TIPS

var query = db.collection.distinct("delete")
db.collection.remove({ delete : {$in : query} })

Be careful : It will remove every document having the delete key

If you supply some document sample, the answers you will get can be more specific and accurate.

There might be confusion over distinct here. You said 'documents that contain the word delete'. A question is which field does the word "delete" appear in?

The distinct () command you issue returns to you distinct values from a field named "delete", not ids of documents where the word "delete" appears in some field value.

For instance, if you have a record

{_id:1, x:"delete"}
{_id:2,delete:true}
{_id:3,delete:null}
{_id:4,delete:false}
{_id:5, x:"leave alone"}

you would remove the first document with

db.foo.remove({x:"delete"})

you would remove the second record with

db.foo.remove({delete:true})

you would remove records 2,3,4 with

db.foo.remove({delete:{$exists:true}})

There is no need to first query out all the records into the shell and then compose a query from them. You can specify the criteria directly to the remove command.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top