10

I am attempting to delete all the documents returned by an aggregation in Mongodb.

The query I have is as follows:

db.getCollection("Collection")
  .aggregate([
    {
      $match: { status: { $in: ["inserted", "done", "duplicated", "error"] } }
    },
    {
      $project: {
        yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }
      }
    },  
    { $match: { yearMonthDay: { $eq: "2019-08-06" } } }
  ])
  .forEach(function(doc) {
    db.getCollection("Collection").remove({});
  });

I tried this query but it removes all the data in the database, any suggestions please?

2 Answers 2

26

Since the remove doesn't have a query condition its going to match with all the documents and delete irrespective of the aggregation result.

Solution (match the ids of the current cursor doc):

db.getCollection("Collection")
  .aggregate([
    {
      $match: { status: { $in: ["inserted", "done", "duplicated", "error"] } }
    },
    {
      $project: {
        yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }
      }
    },
    { $match: { yearMonthDay: { $eq: "2019-08-06" } } }
  ])
  .forEach(function(doc) {
    db.getCollection("Collection").remove({ "_id": doc._id });
  });

Another better solution would be to have single round trip to db while deletion is get a list of ids from the aggregation cursor() via cursor.map()

var idsList = db
  .getCollection("Collection")
  .aggregate([
    {
      $match: { status: { $in: ["inserted", "done", "duplicated", "error"] } }
    },
    {
      $project: {
        yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }
      }
    },
    { $match: { yearMonthDay: { $eq: "2019-08-06" } } }
  ])
  .map(function(d) {
    return d._id;
  });

//now delete those documents via $in operator
db.getCollection("Collection").remove({ _id: { $in: idsList } });
8
  • Thanks for nswer, I will try that then i get u back
    – user11459242
    Nov 6, 2019 at 13:12
  • 1
    Thnaks it works I have another question please, I can execute the second one using a js file ?
    – user11459242
    Nov 6, 2019 at 13:23
  • Yes it'll work in the shell as well as in a js file. Nov 6, 2019 at 13:25
  • thanks, but I will have to mention the connectionstring to mongo or I put just this code ?
    – user11459242
    Nov 6, 2019 at 13:27
  • U can execute a js file directly from the mongo shell but I sense that's not what u'are looking for, and probably u want this code to run in node.js or something.. then yes connection string and collection instance and all that is required. link Nov 6, 2019 at 13:32
4

As per your query its not required to filter by aggregation and remove by another methods, you can apply this query filters in remove() method's filters,

  • the $expr Allows the use of aggregation expressions within the query language,
db.getCollection("Collection").remove({ 
  $and: [
    { status: { $in: ["inserted", "done", "duplicated", "error"] } },
    {
      $expr: {
        $eq: [
          { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
          "2019-08-06"
        ]
      }
    }
  ]
});

This can also support in deleteOne and deleteMany methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy