Murat Karagöz
Murat Karagöz

Reputation: 37584

MongoDB - Is it possible to remove all documents with a certain field referenced?

I have Documents which have a reference key to another Document. Is it possible to remove every Document which has a reference to that field in one go?

Right now, I would use db.collection.remove(<query for the reference>) and run it through every single collection, but this does not seem efficient at all.

What I want to do is to use one single remove query which would run through all documents. I am using the command prompt in RoboMongo.

Upvotes: 1

Views: 1140

Answers (1)

Mohamed Amjad LASRI
Mohamed Amjad LASRI

Reputation: 448

The answer to your first question is yes you can do it.

How you can do it: If you want to perform actions like that, you can write a small mongoDB script. learn more about mongo shell scripts

A solution to your post could be a script like that:

cursor = db.collection.find();
while ( cursor.hasNext() ) {
   // Compare the two keys and remove the appropriate document
}

MongoDB Shell Scripting is a good solution if you have to automate actions.

Upvotes: 1

Related Questions