EdWood
EdWood

Reputation: 907

MongoDB - move documents to archive and delete them from original collection

I have two collections:

I want to move all documents, which match some condition, to collection B (archive) and original documents from collection A remove. I use Python and so far I have this:

db.A.aggregate([{"$match": {"$and": [{"attribute1": False}, {"attribute2": False}]} }, {"$out": "B"} ])

db.A.deleteMany({"$and": [{"attribute1": False}, {"attribute2": False}]})

Both commands work, but when I call deleteMany on collection A it also deletes new documents in archive B. I guess Mongo keeps it like one object and share some kind of pointer and that's why it removes from both collections. Any idea how to solve it?

Upvotes: 0

Views: 2754

Answers (1)

EdWood
EdWood

Reputation: 907

Solution for Python:

documents = db.A.find({"attribute1": False, "attribute2": False})
if documents.count() != 0:
    db.B.insert_many(documents)
    db.A.remove({"attribute1": False, "attribute2": False})

Upvotes: 1

Related Questions