Setup the plain MongoDB connection
189895
function(callback)
    {
        // Connect to the given URI with the given options
        self.mongo.MongoClient.connect(self.config.uri, defaultOpts, function(err, db) {

            if (err) {
                return callback && callback(err);
            }

            // Rewrite connection
            self.connection = db;

            callback && callback(null, db);
        });
    }
406857
def _construct_mongod(self, dbpath, logpath, port, replset=None, extra=''):
        """"""
        rs_param = ''
        if replset:
            rs_param = '--replSet %s' % replset

        auth_param = ''
        if self.args['auth']:
            key_path = os.path.abspath(os.path.join(self.dir, 'keyfile'))
            auth_param = '--keyFile %s' % key_path

        if self.unknown_args:
            config = '--configsvr' in extra
            extra = self._filter_valid_arguments(self.unknown_args, "mongod",
                                                 config=config) + ' ' + extra

        # set WiredTiger cache size to 1 GB by default
        if ('--wiredTigerCacheSizeGB' not in extra and
                self._filter_valid_arguments(['--wiredTigerCacheSizeGB'],
                                             'mongod')):
            extra += ' --wiredTigerCacheSizeGB 1 '

        current_version = self.getMongoDVersion()

        # Exit with error if hostname is specified but not bind_ip options
        if (self.args['hostname'] != 'localhost'
                and LooseVersion(current_version) >= LooseVersion("3.6.0")
                and (self.args['sharded'] or self.args['replicaset'])
                and '--bind_ip' not in extra):
            os.removedirs(dbpath)
            errmsg = " \n * If hostname is specified, please include "\
                "'--bind_ip_all' or '--bind_ip' options when deploying "\
                "replica sets or sharded cluster with MongoDB version 3.6.0 "\
                "or greater"
            raise SystemExit(errmsg)

        extra += self._get_ssl_server_args()

        path = self.args['binarypath'] or ''
        if os.name == 'nt':
            newdbpath = dbpath.replace('\\', '\\\\')
            newlogpath = logpath.replace('\\', '\\\\')
            command_str = ("start /b \"\" \"%s\" %s --dbpath \"%s\" "
                           " --logpath \"%s\" --port %i "
                           "%s %s" % (os.path.join(path, 'mongod.exe'),
                                      rs_param, newdbpath, newlogpath, port,
                                      auth_param, extra))
        else:
            command_str = ("\"%s\" %s --dbpath \"%s\" --logpath \"%s\" "
                           "--port %i --fork "
                           "%s %s" % (os.path.join(path, 'mongod'), rs_param,
                                      dbpath, logpath, port, auth_param,
                                      extra))

        # store parameters in startup_info
        self.startup_info[str(port)] = command_str
964929
@PostConstruct
    public void initDatabase() {
        MongoDBInit.LOGGER.info("initializing MongoDB");
        String dbName = System.getProperty("mongodb.name");
        if (dbName == null) {
            throw new RuntimeException("Missing database name; Set system property 'mongodb.name'");
        }
        MongoDatabase db = this.mongo.getDatabase(dbName);

        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:mongodb/*.ndjson");
            MongoDBInit.LOGGER.info("Scanning for collection data");
            for (Resource res : resources) {
                String filename = res.getFilename();
                String collection = filename.substring(0, filename.length() - 7);
                MongoDBInit.LOGGER.info("Found collection file: {}", collection);
                MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);
                try (Scanner scan = new Scanner(res.getInputStream(), "UTF-8")) {
                    int lines = 0;
                    while (scan.hasNextLine()) {
                        String json = scan.nextLine();
                        Object parse = JSON.parse(json);
                        if (parse instanceof DBObject) {
                            DBObject dbObject = (DBObject) parse;
                            dbCollection.insertOne(dbObject);
                        } else {
                            MongoDBInit.LOGGER.error("Invalid object found: {}", parse);
                            throw new RuntimeException("Invalid object");
                        }
                        lines++;
                    }
                    MongoDBInit.LOGGER.info("Imported {} objects into collection {}", lines, collection);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error importing objects", e);
        }
    }
1239575
function connect(obj, cb) {
    if (obj.db) {
        return cb();
    }
    if (obj.pending) {
        return setImmediate(function () {
            connect(obj, cb);
        });
    }
    obj.pending = true;

    var url = constructMongoLink(obj.config.name, obj.config.prefix, obj.config.servers, obj.config.URLParam, obj.config.credentials);
    if (!url) {
        return cb(generateError(190));
    }

    mongoSkin.connect(url, obj.config.extraParam, function (err, db) {
        if (err) {
            obj.pending = false;
            return cb(err);
        } else {
            db.on('timeout', function () {
                console.log("Connection To Mongo has timed out!");
                obj.flushDb();
            });
            db.on('close', function () {
                console.log("Connection To Mongo has been closed!");
                obj.flushDb();
            });
            if (obj.db)
                obj.db.close();

            obj.db = db;
            obj.pending = false;
            return cb();
        }
    });

    /**
     *constructMongoLink: is a function that takes the below param and return the URL need to by mongoskin.connect
     *
     * @param dbName
     * @param prefix
     * @param servers
     * @param params
     * @param credentials
     * @returns {*}
     */
    function constructMongoLink(dbName, prefix, servers, params, credentials) {
        if (dbName && Array.isArray(servers)) {
            var url = "mongodb://";
            if (credentials && Object.hasOwnProperty.call(credentials, 'username') && credentials.hasOwnProperty.call(credentials, 'password')) {
                url = url.concat(credentials.username, ':', credentials.password, '@');
            }

            servers.forEach(function (element, index, array) {
                url = url.concat(element.host, ':', element.port, (index === array.length - 1 ? '' : ','));
            });

            url = url.concat('/');
            if (prefix) url = url.concat(prefix);
            url = url.concat(dbName);

            if (params && 'object' === typeof params && Object.keys(params).length) {
                url = url.concat('?');
                for (var i = 0; i < Object.keys(params).length; i++) {
                    url = url.concat(Object.keys(params)[i], '=', params[Object.keys(params)[i]], i === Object.keys(params).length - 1 ? '' : "&");
                }
            }
            return url;
        }
        return null;
    }
}
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);
  });
}
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
11515
def collect(self):
        """"""

        if pymongo is None:
            self.log.error('Unable to import pymongo')
            return

        # we need this for backwards compatibility
        if 'host' in self.config:
            self.config['hosts'] = [self.config['host']]

        # convert network_timeout to integer
        if self.config['network_timeout']:
            self.config['network_timeout'] = int(
                self.config['network_timeout'])

        # use auth if given
        if 'user' in self.config:
            user = self.config['user']
        else:
            user = None

        if 'passwd' in self.config:
            passwd = self.config['passwd']
        else:
            passwd = None

        for host in self.config['hosts']:
            if len(self.config['hosts']) == 1:
                # one host only, no need to have a prefix
                base_prefix = []
            else:
                matches = re.search('((.+)\@)?(.+)?', host)
                alias = matches.group(2)
                host = matches.group(3)

                if alias is None:
                    base_prefix = [re.sub('[:\.]', '_', host)]
                else:
                    base_prefix = [alias]

            try:
                if ReadPreference is None:
                    conn = pymongo.Connection(
                        host,
                        network_timeout=self.config['network_timeout'],
                        slave_okay=True
                    )
                else:
                    conn = pymongo.Connection(
                        host,
                        network_timeout=self.config['network_timeout'],
                        read_preference=ReadPreference.SECONDARY,
                    )
            except Exception as e:
                self.log.error('Couldnt connect to mongodb: %s', e)
                continue

            # try auth
            if user:
                try:
                    conn.admin.authenticate(user, passwd)
                except Exception as e:
                    self.log.error(
                        'User auth given, but could not autheticate' +
                        ' with host: %s, err: %s' % (host, e))
                    return{}

            serverStatus = conn.db.command('serverStatus')
            engineStatus = conn.db.command('engineStatus')
            data = dict(serverStatus.items() + engineStatus.items())

            self._publish_transformed(data, base_prefix)
            if str_to_bool(self.config['simple']):
                data = self._extract_simple_data(data)

            self._publish_dict_with_prefix(data, base_prefix)
            db_name_filter = re.compile(self.config['databases'])
            ignored_collections = re.compile(self.config['ignore_collections'])
            for db_name in conn.database_names():
                if not db_name_filter.search(db_name):
                    continue
                db_stats = conn[db_name].command('dbStats')
                db_prefix = base_prefix + ['databases', db_name]
                self._publish_dict_with_prefix(db_stats, db_prefix)
                for collection_name in conn[db_name].collection_names():
                    if ignored_collections.search(collection_name):
                        continue
                    collection_stats = conn[db_name].command('collstats',
                                                             collection_name)
                    if str_to_bool(self.config['translate_collections']):
                        collection_name = collection_name.replace('.', '_')
                    collection_prefix = db_prefix + [collection_name]
                    self._publish_dict_with_prefix(collection_stats,
                                                   collection_prefix)
336980
function parseMongoConnectionOptions(req, res, next) {
  var options = {};
  options.uri = req.mongoUrl;

  req.connectionOptions = options;

  return next();
}
858252
def cli(ctx, database, username, password, authdb, port, host, uri, verbose, config, test):
    """"""
    loglevel = "INFO"
    if verbose:
        loglevel = "DEBUG"
    coloredlogs.install(level=loglevel)
    LOG.info("Running loqusdb version %s", __version__)

    configs = {}
    if config:
        try:
            configs = yaml.safe_load(config)
        except yaml.YAMLError as err:
            LOG.warning(err)
            ctx.abort()
    
    uri = configs.get('uri') or uri
    if test:
        uri = "mongomock://"
    try:
        client = get_client(
            host=configs.get('host') or host,
            port=configs.get('port') or port,
            username=configs.get('username') or username,
            password=configs.get('password') or password,
            authdb=authdb or database or 'loqusdb',
            uri=uri,
        )
    except DB_Error as err:
        LOG.warning(err)
        ctx.abort()
    
    database = configs.get('db_name') or database
    
    if not database:
        database = 'loqusdb'
        if uri:
            uri_info = uri_parser.parse_uri(uri)
            database = uri_info.get('database')

    adapter = MongoAdapter(client, db_name=database)

    ctx.obj = {}
    ctx.obj['db'] = database
    ctx.obj['user'] = username
    ctx.obj['password'] = password
    ctx.obj['port'] = port
    ctx.obj['host'] = host
    ctx.obj['adapter'] = adapter
    ctx.obj['version'] = __version__
224250
function Fossa(options) {
  this.fuse();

  //
  // Store the options.
  //
  this.writable('queue', []);
  this.writable('plugins', {});
  this.writable('connecting', false);
  this.readable('options', configure(options || {}, this));

  //
  // Prepare a default model and collection sprinkled with MongoDB proxy methods.
  //
  this.readable('Model', model(this));
  this.readable('Collection', collection(this));

  //
  // Provide reference to the orginal mongo module so it can be used easily.
  //
  this.readable('mongo', mongo);

  //
  // Prepare connection.
  //
  this.init(
    this.options('hostname', 'localhost'),
    this.options('port', 27017),
    this.options
  );
}
119709
def mongo_client(*args, **kwargs):
    

    kwargs = kwargs or {}
    connection_timeout_ms = kwargs.get("connectTimeoutMS") or CONN_TIMEOUT_MS

    kwargs.update({
        "socketTimeoutMS": connection_timeout_ms,
        "connectTimeoutMS": connection_timeout_ms,
        "maxPoolSize": 1
    })

    if pymongo.get_version_string().startswith("3.2"):
        if kwargs and kwargs.get("serverSelectionTimeoutMS") is None:
            kwargs["connect"] = True
            kwargs["serverSelectionTimeoutMS"] = connection_timeout_ms

    return _mongo_client(*args, **kwargs)
759380
function buildDbConfig(appName, config) {
    var dbDriver = fetchFromConfig(appName, config, 'dbDriver') || 'mongo';
    var defaultPort = dbDriver === 'mongo' ? 27017 : 5432;
    return {
        dbName:         fetchFromConfig(appName, config, 'dbName'),
        dbPath:         fetchFromConfig(appName, config, 'dbPath'),
        dbDriver:       dbDriver,
        dbType:         fetchFromConfig(appName, config, 'dbType')        || 'mongo',
        dbUser:         fetchFromConfig(appName, config, 'dbUser')        || 'nodejs',
        dbPassword:     fetchFromConfig(appName, config, 'dbPassword')    || null,
        dbConnections:  parseInt(fetchFromConfig(appName, config, 'dbConnections')) || 20,
        dbConcurrency:  parseInt(fetchFromConfig(appName, config, 'dbConcurrency')) || 5,
        dbConnectionTimeout: parseInt(fetchFromConfig(appName, config, 'dbConnectionTimeout')) || 60000,
        dbPort: fetchFromConfig(appName, config, 'dbPort') || defaultPort,
        knexDebug: fetchFromConfig(appName, config, 'knexDebug') || false
    };
}
1133239
function getMongooseConnection(mongoDbUrl, logger, cb) {
  logger.debug("creating mongoose connection for data_source_update job", {mongoDbUrl: mongoDbUrl});
  var mongooseConnection = mongoose.createConnection(mongoDbUrl);
  return cb(undefined, mongooseConnection);
}
944800
function getMongodbConnection(mongoDbUrl, logger, cb) {
  logger.debug("creating mongodb connection for data_source_update job", {mongoDbUrl: mongoDbUrl});
  MongoClient.connect(mongoDbUrl, cb);
}
392362
def setup(
            self):
        

        return self.arguments, self.settings, self.log, self.dbConn
264703
function MongoDB () {
  var self = this;

  self.klass = MongoDB;
  self.klass.super_.apply(self, arguments);
}
537464
function() {
      const AUTH_TOKEN = 'AUTH_TOKEN';
      var req = {
        protocol: this.isSrvRecord ? 'mongodb+srv' : 'mongodb',
        slashes: true,
        hostname: this.hostname,
        port: this.isSrvRecord ? null : this.port,
        pathname: '/',
        query: {}
      };

      if (this.replica_set_name) {
        req.query.replicaSet = this.replica_set_name;
      }

      req.query.readPreference = this.read_preference;

      if (this.app_name) {
        req.query.appname = this.app_name;
      }

      if (this.ns) {
        req.pathname = format('/%s', this.ns);
      }

      const encodeAuthForUrlFormat = () => {
        if (this.authentication === 'MONGODB') {
          req.auth = AUTH_TOKEN;
          req.query.authSource = this.mongodb_database_name || MONGODB_DATABASE_NAME_DEFAULT;
        } else if (this.authentication === 'SCRAM-SHA-256') {
          req.auth = AUTH_TOKEN;
          req.query.authSource = this.mongodb_database_name || MONGODB_DATABASE_NAME_DEFAULT;
          req.query.authMechanism = this.driver_auth_mechanism;
        } else if (this.authentication === 'KERBEROS') {
          defaults(req.query, {
            gssapiServiceName: this.kerberos_service_name,
            authMechanism: this.driver_auth_mechanism
          });
          req.auth = AUTH_TOKEN;
        } else if (this.authentication === 'X509') {
          req.auth = this.x509_username;
          defaults(req.query, {
            authMechanism: this.driver_auth_mechanism
          });
        } else if (this.authentication === 'LDAP') {
          req.auth = AUTH_TOKEN;

          defaults(req.query, {
            authMechanism: this.driver_auth_mechanism
          });
        }
      };
      encodeAuthForUrlFormat();

      if (includes(['UNVALIDATED', 'SYSTEMCA', 'SERVER', 'ALL'], this.ssl)) {
        req.query.ssl = 'true';
      } else if (this.ssl === 'IFAVAILABLE') {
        req.query.ssl = 'prefer';
      } else if (this.ssl === 'NONE') {
        req.query.ssl = 'false';
      }
      var reqClone = clone(req);
      if (this.ssh_tunnel !== 'NONE') {
        // Populate the SSH Tunnel options correctly
        reqClone.hostname = this.ssh_tunnel_options.localAddr;
        reqClone.port = this.ssh_tunnel_options.localPort;
      }
      var result = toURL(reqClone);

      // Post url.format() workaround for
      // https://github.com/nodejs/node/issues/1802
      if (this.authentication === 'MONGODB' || this.authentication === 'SCRAM-SHA-256') {
        const authField = format(
          '%s:%s',
          encodeURIComponent(this.mongodb_username),
          encodeURIComponent(this.mongodb_password)
        );

        // The auth component comes straight after the mongodb:// so
        // a single string replace should always work
        result = result.replace(AUTH_TOKEN, authField, 1);
      }
      if (this.authentication === 'LDAP') {
        const authField = format(
          '%s:%s',
          encodeURIComponent(this.ldap_username),
          encodeURIComponent(this.ldap_password)
        );
        result = result.replace(AUTH_TOKEN, authField, 1);
        result = `${result}&authSource=$external`;
      }
      if (this.authentication === 'KERBEROS') {
        if (this.kerberos_password) {
          const authField = format(
            '%s:%s',
            encodeURIComponent(this.kerberos_principal),
            encodeURIComponent(this.kerberos_password)
          );
          result = result.replace(AUTH_TOKEN, authField, 1);
        } else {
          const authField = format(
            '%s:',
            encodeURIComponent(this.kerberos_principal)
          );
          result = result.replace(AUTH_TOKEN, authField, 1);
        }
        result = `${result}&authSource=$external`;
        if (this.kerberos_canonicalize_hostname) {
          result = `${result}&authMechanismProperties=CANONICALIZE_HOST_NAME:true`;
        }
      }
      return result;
    }