Last active
December 15, 2020 07:33
-
-
Save swateek/e6e76fe2cdac733371c9e0bd1ceb0698 to your computer and use it in GitHub Desktop.
All Pymongo Snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!./pymUEnv/bin/python | |
from pymongo import MongoClient | |
mongo_prefix = "mongodb://" | |
mongo_server = "127.0.0.1" | |
mongo_port = "28000" | |
mongodb_uri = mongo_prefix + mongo_server + ":" + mongo_port | |
client = MongoClient(mongodb_uri) | |
source_db = "tmp1" | |
target_db = "tmp2" | |
admin_db = "admin" | |
source_collection = "people" | |
target_collection = "people" | |
sdb = client[source_db] | |
tdb = client[target_db] | |
adminDB = client[admin_db] | |
# Step 1: Drop Test DB | |
print("Dropping Databases before start of test..") | |
client.drop_database(source_db) | |
client.drop_database(target_db) | |
# Step 2: Insert Recs | |
print("Inserting Sample Records..") | |
recs = [{'name':'swateek'}, {'name':'ricky'}] | |
sdb[source_collection].insert_many(recs) | |
# Step 3: Fetch Recs to Ensure Insertion | |
print("Checking Sample Records at Source..") | |
resp = sdb[source_collection].find() | |
for doc in resp: | |
print(doc) | |
# Step 4: Move the collection | |
print("Moving Collection..") | |
src = source_db + "." + source_collection | |
dest = target_db + "." + target_collection | |
db_resp = adminDB.command({'renameCollection': src, 'to': dest}) | |
# Step 5: Check in Source DB, if anything exists. | |
print("Checking Sample Records at Source..") | |
resp = list(sdb[source_collection].find()) | |
print(resp) | |
print("Checking Sample Records at Destination..") | |
# Step 6: Check in Target DB. | |
resp = list(tdb[target_collection].find()) | |
print(resp) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Everything Pymongo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment