user13296357
user13296357

Reputation: 11

how to delete many documents from a collection based on a condition with values from an other collection

here is attached the aggregate query i want to delete all the returning values of this query from the same collection "History" how to do it ?

enter image description here

lets say i have a collection of stock-market companies records named "history" as

{_id:"value",symbol:"value",date:"value",open:"value",close:"value",......}

my file is supposed to have a document for each company for each day , in total 42days of records for each company but after checking the data it seems like some companies doesn't have all the 42days records "one document/day" they have less so i want to delete the companies who doesn't have exactly 42 documents my group by will be on the "symbol" my count on "date" i can get the list but i don't know how to delete it

Upvotes: 1

Views: 818

Answers (1)

Valijon
Valijon

Reputation: 13103

You can remove them running .remove method.

db.history.aggregate(...).forEach(function(doc){
    db.history.remove({symbol: doc._id});
})

Note: It's very slow.

Alternative solution: Change aggregation criteria to return valid documents and override history collection with $out operator:

db.history.aggregate([
  {
    $group: {
      _id: "$symbol",
      nbr_jours: {
        $sum: 1
      },
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $match: {
      nbr_jours: {
        $gte: 42 //$eq
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  },
  {
    $out: "history"
  }
])

Note: It's very fast.

Upvotes: 1

Related Questions