mongodbmongodb-query

Delete documents from collection based on condition


I want to delete the documents from a collection(Collection1) which are not matching with other collection(Collection2).

collection1 document - {_id: <autogen>, items: [{key:'key', ...}}]

collection2 document - {_id: 'key', action: {key1:'key1', ...}}, {_id: 'non_matching_key', action: {key1:'key1', ...}}

Delete all the documents from collection2, where items.key in collection1 is not matching with _id in collection2. with reference to the above example, a document with key-value 'non_matching_key' should be delete from collection2. There would be similar documents in collection2 like the one with _id value 'non_matching_key'.

The approach I thought was for mark and sweep.

Could you please advise if there is a better way of doing this?


Solution

  • Not fully clear how your documents look like and what are the exact conditions, but you could do it like this:

    var ids = db.collection1.find({}, { "item.key": 1 }).toArray();
    db.collection2.deleteMany({ _id: { $nin: ids } });