Establish a connection with the database.

        Returns MongoDb collection
354205
def get_collection(self, **kwargs):
        
        from pymongo import MongoClient

        if self.host and self.port:
            client = MongoClient(host=config.host, port=config.port)
        else:
            client = MongoClient()
        db = client[self.dbname]

        # Authenticate if needed
        if self.user and self.password:
            db.autenticate(self.user, password=self.password)

        return db[self.collection]
1166996
function connect(uri, callback) {
  console.log('connecting to database (' + uri + ')');
  mongo.MongoClient.connect(uri, {safe: true}, function (err, client) {
    if (err) return callback(err);

    db = client;
    db.addListener("error", function (error) {
      console.log("mongo client error: " + error);
    });

    callback(null, db);
  });
}
1135307
function start(callback) {
    var dbDeferred = Q.defer();
    config = defaultConfig;

    if (typeof gmeConfig.rest.components[CONFIG_ID] === 'object' &&
        gmeConfig.rest.components[CONFIG_ID].options) {

        config = gmeConfig.rest.components[CONFIG_ID].options;
    }

    mongodb.MongoClient.connect(config.mongo.uri, config.mongo.options, function (err, db) {
        if (err) {
            dbDeferred.reject(err);
        } else {
            dbConn = db;
            dbDeferred.resolve();
        }
    });

    return dbDeferred.promise.nodeify(callback);
}
875261
def connect(self):
        
        self.log.debug('starting the ``get`` method')

        dbSettings = self.dbSettings

        port = False
        if "tunnel" in dbSettings and dbSettings["tunnel"]:
            port = self._setup_tunnel(
                tunnelParameters=dbSettings["tunnel"]
            )

        # SETUP A DATABASE CONNECTION
        host = dbSettings["host"]
        user = dbSettings["user"]
        passwd = dbSettings["password"]
        dbName = dbSettings["db"]
        dbConn = ms.connect(
            host=host,
            user=user,
            passwd=passwd,
            db=dbName,
            port=port,
            use_unicode=True,
            charset='utf8',
            local_infile=1,
            client_flag=ms.constants.CLIENT.MULTI_STATEMENTS,
            connect_timeout=36000,
            max_allowed_packet=51200000
        )
        if self.autocommit:
            dbConn.autocommit(True)

        self.log.debug('completed the ``get`` method')
        return dbConn
884595
function (DB_name, account, pass, onOpenDone) {

		var conn = SR._storage.openDB(DB_name, dbSetting.serverIP, dbSetting.serverPort);

		// load fail
		if (conn === undefined) {
			LOG.error('cannot open DB: ' + DB_name, 'SR.DB');
			return onOpenDone(false);
		}

		// open DB & load the collection data from DB
		conn.open(function (err, client) {

			// check if error
			if (err) {
				LOG.error(err, 'SR.DB');
				return UTIL.safeCall(onOpenDone, false);
			}

			var user_created = false;

			var auth_user = function () {

				// authenticate into the DB
				LOG.sys('authenticating DB [' + DB_name + ']...', 'SR.DB');

				// NOTE: use client.admin().authenticate will force using admin account
				//	   but in general we should not do that

				client.authenticate(account, pass, function (err, replies) {

					if (err) {

						// if this is repeated call
						if (user_created === true) {
							LOG.error(err, 'SR.DB');
							LOG.warn('DB authentication failure', 'SR.DB');
							return UTIL.safeCall(onOpenDone, false);
						}

						// create DB user/pass (assume it's a new DB)
						LOG.warn('auth error, assume DB does not exist, try to create new DB...', 'SR.DB');

						// NOTE: right now this action is always successful, so it's like no auth exists
						//	   might be a bug in MongoDB
						user_created = true;

						client.admin().authenticate(SR.Settings.DB_ADMIN.account, SR.Settings.DB_ADMIN.pass, function (err, replies) {
							if (err) {
								LOG.error(err, 'SR.DB');
								LOG.error('DB admin auth failure, please make sure DB_ADMIN is setup correctly either in system or project setting', 'SR.DB');
								return UTIL.safeCall(onOpenDone, false);
							}

							client.addUser(account, pass, function (err, result) {

								if (err) {
									LOG.error(err, 'SR.DB');
									LOG.warn('DB addUser failure', 'SR.DB');
									return UTIL.safeCall(onOpenDone, false);
								}

								LOG.warn('DB addUser success, re-authenticate', 'SR.DB');
								auth_user();
							});
						});

						return;
					}

					LOG.warn('DB authentication success', 'SR.DB');

					// store client for later access
					l_DBconn[DB_name] = conn;
					l_DBclient[DB_name] = client;
					UTIL.safeCall(onOpenDone, true);
				});
			}

			// perform first DB authentication
			auth_user();
		});
	}
836031
def create(cls, name, database=SYSTEM_DATABASE, type=2):
        

        client = Client.instance()
        api = client.api

        if client.database != database:
            database = client.database

        collection_data = {
            'name': name,
            'type': type,
        }

        data = api.collection.post(data=collection_data)

        collection = Collection(
            name=name,
            database=database,
            api_resource=api.collection,
            api=api,
            kwargs=data
        )

        return collection
1332605
async def create_app_collections(db):
    ''' '''
    futures = []
    for model_class in MongoCollectionMixin.__subclasses__():
        if model_class._meta.concrete is True:
            futures.append(create_collection(db, model_class))

    await asyncio.gather(*futures)
739269
function (config) {
        this.config = core.extend({
            connection: 'mongodb://localhost/mvcjs',
            options: {}
        }, config);
        this.db = mongoose.connect(this.config.connection, this.config.options);
        logger.info('Mongo.construct:', this.config);
    }
201147
public function dbInit()
    {
      $mongo_index = ( (phpversion('mongo') >= '1.5.0') ? ('createIndex') : ('ensureIndex') );
      $this->log("maint: {$mongo_index} on ".$this->getConfig('collection'));
      $this->sessions->$mongo_index(array(
                                          'last_accessed' => 1
                                          ));
      $this->log("maint: {$mongo_index} on ".$this->getConfig('lockcollection'));
      $this->locks->$mongo_index(array(
                                       'created' => 1
                                       ));
    }
1194563
function connection() {
  return {
    ssl: JSON.parse(JSON.stringify(process.env.DATABASE_SSL || "")),
    host: process.env.DATABASE_HOST || "localhost",
    user: process.env.DATABASE_USER || "",
    charset: process.env.DATABASE_CHARSET || "utf8",
    password: process.env.DATABASE_PASS || "",
    database: process.env.DATABASE_NAME || ""
  };
}
885464
def _connect(user=None, password=None, host=None, port=None, database='admin', authdb=None):
    '''
    
    '''
    if not user:
        user = __salt__['config.option']('mongodb.user')
    if not password:
        password = __salt__['config.option']('mongodb.password')
    if not host:
        host = __salt__['config.option']('mongodb.host')
    if not port:
        port = __salt__['config.option']('mongodb.port')
    if not authdb:
        authdb = database

    try:
        conn = pymongo.MongoClient(host=host, port=port)
        mdb = pymongo.database.Database(conn, database)
        if user and password:
            mdb.authenticate(user, password, source=authdb)
    except pymongo.errors.PyMongoError:
        log.error('Error connecting to database %s', database)
        return False

    return conn
1374614
function getCollection(docdbClient, nodeContext) {
    nodeContext.log(`Getting collection:\n${collectionName}\n`);
    var colldef = {id : collectionName};
    return new Promise((resolve, reject) => {
        docdbClient.readCollection(collectionUrl, (err, result) => {
            if (err) {
                if (err.code == HttpStatusCodes.NOTFOUND) {
                    docdbClient.createCollection(databaseUrl, colldef, { offerThroughput: 400 }, (err, created) => {
                        if (err) reject(err)
                        else resolve(created);
                    });
                } else {
                    reject(err);
                }
            } else {
                resolve(result);
            }
        });
    });
}
830410
def raw_query_mongo_db(kwargs, database_name, collection_name):
    # for key in kwargs:
    #    print "arg: %s: %s" % (key, kwargs[key])
    """"""
    l = []
    response_dict = {}

    try:
        mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
                                 'mongodb://localhost:27017/')
        mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
        db = mc[database_name]
        transactions = db[collection_name]
        mysearchresult = transactions.find(kwargs)
        mysearchcount = mysearchresult.count()
        if mysearchcount > 0:
            response_dict['code'] = 200
            for d in mysearchresult:
                l.append(d)
            response_dict['results'] = l
    except:
        # print "Error reading from Mongo"
        # print str(sys.exc_info())
        response_dict['code'] = 400

        response_dict['type'] = "Error"
        response_dict['message'] = str(sys.exc_info())
    return response_dict
1028194
async function connect (mongoose, connectionName, connectionOpts) {
  const isDefault = connectionName === 'default'

  // Normalize and destructure connection options
  if (typeof connectionOpts === 'string') {
    connectionOpts = { uri: connectionOpts }
  }
  let { uri, options, forceReconnect } = connectionOpts

  // Apply default options
  // https://mongoosejs.com/docs/connections.html#options
  options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    ...options
  }

  // Manualy create connection
  let conn
  if (isDefault) {
    conn = mongoose.connection
  } else {
    conn = new mongoose.Connection(mongoose)
    mongoose.connections.push(conn)
  }

  // $logger helper
  conn.$logger = isDefault
    ? consola
    : consola.withTag(connectionName)

  // Log connection events
  logConnectionEvents(conn)

  // $connect helper
  conn.$connect = () => {
    return new Promise((resolve, reject) => {
      conn.openUri(uri, options, (error) => {
        if (error) {
          reject(error)
        } else {
          resolve(conn)
        }
      })
    })
  }

  // Make accessable via mongoose.$connectionName
  mongoose['$' + connectionName] = conn

  // Setup force reconnect
  if (forceReconnect) {
    const timeout = forceReconnect === true ? 1000 : forceReconnect
    conn.on('error', () => {
      conn.close()
    })
    conn.on('disconnected', () => {
      setTimeout(() => { conn.$connect() }, timeout)
    })
  }

  // Connect
  await conn.$connect()
  await conn.$initialConnection
}
521494
def connect(self):
        
        LOGGER.debug('Creating a%s connection to %s:%s (db %s)',
                     ' cluster node'
                     if self._clustering else '', self._hosts[0]['host'],
                     self._hosts[0]['port'], self._hosts[0].get(
                         'db', DEFAULT_DB))
        self._connect_future = concurrent.Future()
        conn = _Connection(
            self._hosts[0]['host'],
            self._hosts[0]['port'],
            self._hosts[0].get('db', DEFAULT_DB),
            self._read,
            self._on_closed,
            self.io_loop,
            cluster_node=self._clustering)
        self.io_loop.add_future(conn.connect(), self._on_connected)
        return self._connect_future
1126076
def user_create(name, passwd, user=None, password=None, host=None, port=None,
                database='admin', authdb=None, roles=None):
    '''
    
    '''
    conn = _connect(user, password, host, port, authdb=authdb)
    if not conn:
        return 'Failed to connect to mongo database'

    if not roles:
        roles = []

    try:
        log.info('Creating user %s', name)
        mdb = pymongo.database.Database(conn, database)
        mdb.add_user(name, passwd, roles=roles)
    except pymongo.errors.PyMongoError as err:
        log.error('Creating database %s failed with error: %s', name, err)
        return six.text_type(err)
    return True
717173
function getConnection(connectionString) {
      return new Promise(function(resolve, reject) {
        // If connectionString is null or undefined, return an error.
        if (_.isEmpty(connectionString)) {
          return reject('getConnection must be called with a mongo connection string');
        }

        // Check if a connection already exists for the provided connectionString.
        var pool = _.findWhere(connections, { connectionString: connectionString });

        // If a connection pool was found, resolve the promise with it.
        if (pool) {
          return resolve(pool.db);
        }

        // If the connection pool has not been instantiated,
        // instantiate it and return the connection.
        MongoClient.connect(connectionString, function(err, database) {
          if (err) {
            return reject(err);
          }

          // Store the connection in the connections array.
          connections.push({
            connectionString: connectionString,
            db: database
          });

          return resolve(database);
        });
      });
    }