1

I am new to Mongo and I have a question about deleting documents using PyMongo.

I have a collection called mycollection. It has documents looking like this:

{
    "field1":"value1",
    "field2":"value2",
    "array_field": [
        "id1",
        "id2
    ]
}

I want to delete all documents in the collection which has id1 in the array_field.

How can I do this? (I am using PyMongo, I would appreciate examples based on it :) )

1

2 Answers 2

1

this should do

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = client["DATABASE"]
col = mydb["mycoll"]
 
query = {"array_field": "id1"}
d = col.delete_many(query)
 
print(f"{d.deleted_count} documents deleted")
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't the query {"array_field": "id1"} will delete only the documents where the array_field is id1 (but not where it is an array containing id1 ?)
1
   db.collection.deleteMany({
      "array_field": {
        $in: [
          "id1"
        ]
      }
    })

Check the mongoplayground link: https://mongoplayground.net/p/nkhSCRyR9K-

https://www.mongodb.com/docs/manual/reference/operator/query/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.