简体   繁体   中英

python mongo db aggregate query for taking backup

In one of the previous posts using db[collection].aggregate([{'$match': {}}, {'$out': collection + timestamp}]) was suggested for taking backup of a collection. But this is creating a temp collection.

I want to use the below query in python format.

db.collection1.find().forEach(function(d){db.collection2.save(d)})

Thanks,

To start out I am assuming you are using the PyMongo library. Here is the documentation for the find function on a collection.

Here is the documantation for the insert_one function on a collection. This is one way to take all the docs from one collection and insert them into another function.

for doc in db.collection1.find({}):
    db.collection2.insert_one(doc)

You can also use the insert_many function to do that same thing in a different way.

db.collection2.insert_many(db.collection1.find({}))

DISCLAIMER: I have NOT fully tested these! Make sure you test it BEFORE relying on the code in ANY way.

This is how you'd do that copy in python:

from pymongo import MongoClient

client = MongoClient()
db = client.yourDBname

n = 0
for r in db.sourceCollection.find():
    db.targetCollection.insert(r)
    n += 1

print "copied",n,"items"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM