Skip to content

Instantly share code, notes, and snippets.

@divjotarora
Created January 4, 2021 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divjotarora/29c523b726933192d563b823a2f8abbd to your computer and use it in GitHub Desktop.
Save divjotarora/29c523b726933192d563b823a2f8abbd to your computer and use it in GitHub Desktop.
Dropping/creating collections with requireApiVersion='1' and majority write concern
from pymongo import MongoClient
from pymongo.errors import OperationFailure
import sys
with MongoClient('mongodb://localhost:27017/?replicaSet=phil') as client:
db = client.foo
coll_name = 'bar'
version = client.admin.command('buildinfo')['version']
print(f'testing against server version {version}')
if sys.argv[-1] == '--setParameter':
for host in client.admin.command('ismaster')['hosts']:
print(f'setting parameter on host {host}')
with MongoClient(f'mongodb://{host}') as host_client:
host_client.admin.command({'setParameter': 1, 'requireApiVersion': '1'})
print('dropping collection')
try:
db.command({
'drop': coll_name,
'apiVersion': '1',
'writeConcern': {
'w': 'majority',
},
})
except OperationFailure as err:
# Ignore NamespaceNotFound errors
if err.code != 26:
raise err
print('creating collection')
db.command({
'create': coll_name,
'apiVersion': '1',
'writeConcern': {
'w': 'majority',
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment