Home > Net >  How to delete mulitple ids in mongdb but only 1 document per 1 id?
How to delete mulitple ids in mongdb but only 1 document per 1 id?

Time:10-12

How to delete mulitple ids in mongdb but only 1 document per 1 id? For example I have this collection:

{
    'id': 0
},
{
    'id': 0
},
{
    'id': 1
},

And I need to remove document with {id: {'$in': [0, 5]}}. But only 1 document for every id. I want to get this result after my operation:

{
    'id': 0
}

How to do it?

CodePudding user response:

This can be achieved using a hybrid between Mongo Query Language and a programming language OS your choice to perform the deletion part.

The below example uses JavaScript and can be executed on Mongo Shell.

var resp = db.collection.aggregate([
  {
    "$group": {
      "_id": "$id",
      "idToRemove": {
        "$first": "$_id"
      }
    }
  },
  {
    "$group": {
      "_id": null,
      "idsToRemove": {
        "$push": "$idToRemove"
      }
    }
  },
]).toArray()
db.collection.deleteMany({"_id": {"$in": resp[0]["idsToRemove"]}})

CodePudding user response:

Bulk write would be a way to do that, with a separate deleteOne operation for each _id value.

  • Related