Find an object or list of objects in a collection

    CLI Example:

    .. code-block:: bash

        salt '*' mongodb.find mycollection '[{"foo": "FOO", "bar": "BAR"}]' <user> <password> <host> <port> <database>
10405
def find(collection, query=None, user=None, password=None,
         host=None, port=None, database='admin', authdb=None):
    '''
    

    '''
    conn = _connect(user, password, host, port, database, authdb)
    if not conn:
        return 'Failed to connect to mongo database'

    try:
        query = _to_dict(query)
    except Exception as err:
        return err

    try:
        log.info("Searching for %r in %s", query, collection)
        mdb = pymongo.database.Database(conn, database)
        col = getattr(mdb, collection)
        ret = col.find(query)
        return list(ret)
    except pymongo.errors.PyMongoError as err:
        log.error("Searching objects failed with error: %s", err)
        return err
623886
def get_instance(self, collection, obj_id, **kwargs):
        
        logging.info("Getting single record")
        try:
            obj_id = ObjectId(obj_id)
        except InvalidId:
            logging.error("Invalid ObjectId: {}".format(obj_id))
            return {}
        projection = kwargs.get('projection', {})
        projection = None if len(projection) < 1 else projection
        query = kwargs.get('query', {})
        query.update({'_id': obj_id})
        logging.debug("Query: {}".format(query))
        logging.debug("Projection: {}".format(projection))
        record = self.db[collection].find_one(query, projection)
        return record
82884
def find_by_user(user: str) -> List['ApiKey']:
        
        return [ApiKey.from_db(key) for key in db.get_keys(qb.from_dict({'user': user}))]
69909
def find(self, *args, **kwargs):
    " "
    return Query(*args, db=self, schema=self.schema)
827680
def by_id(cls, oid):
        """"""
        if oid:
            d = cls.collection.find_one(ObjectId(oid))
            if d:
                return cls(**d)
1046812
def find(self, name):
        
        collectors = self.get_collectors()

        for collector in collectors:
            if name.lower() == collector['name'].lower():
                self.collector_id = collector['id']
                return collector

        return {'status': 'No results found.'}
689358
def find(cls, id='', slug=None):
        

        if not id and not slug:
            return None
        try:
            return cls.where(id=id, slug=slug).next()
        except StopIteration:
            raise PanoptesAPIException(
                "Could not find collection with slug='{}'".format(slug)
            )
382859
function MongoDB(config) {

	if (!config) {
		throw new Error("Expected a MongoDB configuration");
	}
	if (!config.url) {
		throw new Error("Expected a url in the MongoDB configuration");
	}
	if (!config.collection) {
		throw new Error("Expected a collection in the MongoDB configuration");
	}

	var self = this
		, mongooseInstance = new Mongoose()
		, internalConnection
		, EARTH_RADIUS = 6378000; // in meters

	this.name = config.name;
	this.type = "MongoDB";

	this.connect = function connect(callback) {

		if (internalConnection) {
			process.nextTick(function () {
				callback(null, internalConnection);
			});
		}
		else {
			mongooseInstance.connect(config.url);
			mongooseInstance.connection.once('open', function (err) {
				if (err) { return callback(err); }

				internalConnection = mongooseInstance.connection;
				callback(null, internalConnection);
			});
		}
	};

	/**
	 * Get a document by the tehcnical ObjectId.
	 * @param id
	 * @param callback
	 */
	this.getById = function getById(id, callback) {
		self.connect(function (err, connection) {
			if (err) { return callback(err); }
			connection.db.collection(config.collection, function (err, collection) {
				collection.findOne({ "_id": id }, function (err, result) {
					callback(err, result);
				});
			});
		});
	};

	/**
	 * Get a specific document by name index
	 * @param name
	 * @param callback
	 */
	this.getByName = function getByName(name, callback) {
		return self.getByKey({ name: name}, callback);
	};

	/**
	 * Get a specific document, having a filter on field.
	 * @param filter
	 * @param callback
	 */
	this.getByKey = function getByKey(filter, callback) {
		if (!filter) { throw new Error("Argument filter cannot be null or undefined!"); }
		self.connect(function (err, connection) {
			if (err) { return callback(err); }
			return connection.db.collection(config.collection, function (err, collection) {
				collection.find(filter).toArray(function (err, result) {
					callback(err, result);
				});
			});
		});
	};

	/**
	 * Save method to mongoDB means a whole document replacement, which is not advisable due to
	 * efficiency reasons. Use update method instead.
	 * @param key
	 * @param value
	 * @param callback
	 */
	this.save = function save(key, value, callback) {
		if (!key) { throw new Error("Argument key is missing."); }
		if (!value) { throw new Error("Argument value is missing."); }
		//if (!callback) { throw new Error("Argument callback is missing"); }
		callback = callback || function () {
			return;
		};

		self.connect(function (err, connection) {
			if (err) { return callback(err); }

			connection.db.collection(config.collection, function (err, collection) {
				collection.save(value, {safe: true}, function (err, result) {
					callback(err, result);
				});
			});
		});
	};

//	/**
//	 * Save method is a whole document replacement, which is not advisable due to
//	 * efficiency reasons. Use update method instead.
//	 * @param object
//	 * @param callback
//	 */
//	this.save = function save(object, callback) {
//		self.connect(function (err, connection) {
//
//			if (err) { return callback(err); }
//
//			connection.db.collection(config.collection, function (err, collection) {
//				collection.save(object, {safe: true}, function (err, result) {
//					callback(err, result);
//				});
//			});
//		});
//	};

	/**
	 * Update method helps updating specific fields of the document. It has a built in
	 * insert function and should be used instead of save.
	 * @param parameters
	 * @param callback
	 */
	this.update = function update(parameters, callback) {

		if (!parameters || (parameters instanceof Function && !callback)) {
			throw new Error("Cannot execute udate without options.");
		}
		if (!parameters.selector) {
			throw new Error("Cannot execute update without a selector.");
		}
		if (!parameters.updateValues) {
			throw new Error("Cannot execute update without one or more update values.");
		}
		if (!parameters.options) {
			parameters.options = { safe: true };
		}

		var selector = parameters.selector
			, updateValues = { $set: parameters.updateValues }
			, options = parameters.options;

		self.connect(function (err, connection) {
			if (err) { return callback(err); }

			connection.db.collection(config.collection, function (err, collection) {
				collection.update(selector, updateValues, options, function (err, result) {

					callback(err, result);
				});
			});
		});
	};

	/**
	 * Remove a document from collection by given selector.
	 * @param selector
	 * @param callback
	 */
	this.remove = function remove(selector, callback) {

		self.connect(function (err, connection) {
			if (err) { return callback(err); }

			connection.db.collection(config.collection, function (err, collection) {
				collection.remove(selector, function (err, result) {
					callback(err, result);
				});
			});

		});
	};

	/**
	 * Get all documents in the collection.
	 * returnLimit parameter is optional and means: return returnLimit documents or nothing
	 * if the produced result count is less that returnLimit.
	 * @param returnLimit
	 * @param callback
	 */
	this.getAll = function getAll(sort, returnLimit, callback) {
		if (sort instanceof Function && !returnLimit && !callback) {
			callback = sort;
			sort = undefined;
			returnLimit = undefined;
		} else if (typeof sort === 'number' && returnLimit instanceof Function) {
			callback = returnLimit;
			returnLimit = sort;
			sort = undefined;
		} else if (typeof sort === 'object' && returnLimit instanceof Function) {
			callback = returnLimit;
			returnLimit = undefined;
		} else if (typeof sort === 'object' && typeof returnLimit === 'number' && callback instanceof Function) {
			sort = 'object';
		} else {
			throw new Error("Invalid arguments");
		}

		self.connect(function (err, connection) {
			if (err) { return callback(err); }

			return connection.db.collection(config.collection, function (err, collection) {
				var find = collection.find();

				if (sort) { find = find.sort(sort); }
				if (returnLimit) { find = find.limit(returnLimit); }

				find.toArray(function (err, result) {
					callback(err, result);
				});

			});

		});
	};

	/**
	 *  Get all documents in the collection filtered by a given query.
	 * If no filter query has been passed then throw an error. Use method getAll instead.
	 * returnLimit parameter is optional and means: return returnLimit documents or nothing
	 * if the produced result count is less that returnLimit.
	 * @param filter
	 * @param returnLimit
	 * @param callback
	 * @return {*}
	 */
	this.getAllWithFilter = function getAll(filter, returnLimit, callback) {
		if (!filter || filter instanceof Function) {
			return callback(new Error("No filter query was provided in method getAllWithFilter."));
		}
		if (!returnLimit || returnLimit instanceof Function) {
			callback = returnLimit;
			returnLimit = null;
		}

		self.connect(function (err, connection) {
			if (err) { return callback(err); }

			connection.db.collection(config.collection, function (err, collection) {

				if (returnLimit) {
					collection.find(filter).limit(returnLimit).toArray(function (err, result) {
						return callback(err, result);
					});
				} else {
					collection.find(filter).toArray(function (err, result) {
						return callback(err, result);
					});
				}

			});
		});
	};

	/**
	 * Execute a geo search query with options.
	 * @example
	 * geoSearch([ 4.32244, 52.2323 ], function callback() { });
	 * geoSearch({ 
	 *   locationCenter: [ 4.32244, 52.2323 ],
	 *   query: {},
	 *   maximumResults: 10,
	 *   maximumRange: 100 // in KM
	 * }, function callback() { });
	 * @param {Object|Array} options A geo location or multiple options
	 * @param {Function} callback A callback function
	 */
	this.geoSearch = function geoSearch(options, callback) {

		if (options instanceof Array) {
			options = { locationCenter: options };
		}

		if (!options.locationCenter) {
			throw new Error("Cannot execute geoSearch without locationCenter");
		}

		var filter = {
			geoNear: config.collection,
			near: options.locationCenter,
			spherical: true
		};

		if (options.query) {
			filter.query = options.query;
		}

		if (options.maximumResults) {
			filter.num = options.maximumResults;
		}

		if (options.maximumRange) {
			filter.maxDistance = options.maximumRange / EARTH_RADIUS; // to radians
		}

		self.connect(function (err, connection) {
			if (err) { return callback(err); }

			connection.db.executeDbCommand(filter, function (err, res) {

				if (err) { return callback(err); }
				if (res.documents[0].errmsg) { return callback(new Error(res.documents[0].errmsg)); }

				//res.documents[0].results = [];
				var candidates = res.documents[0].results.map(function (element) {

					if ((element.dis * EARTH_RADIUS) / 1000 < 1) {
						element.distance = Math.round(element.dis * EARTH_RADIUS) + " m";
					}
					else {
						element.distance = Math.round((element.dis * EARTH_RADIUS) / 1000) + " km";
					}

					return element;
				});

				return callback(null, candidates);
			});
		});
	};

	this.disconnect = function disconnect(callback) {
		if (internalConnection) {
			internalConnection = undefined;
		}
		mongooseInstance.disconnect(callback);
	};

	this.dispose = function dispose(callback) {
		// Close connection...
		self.disconnect(callback);
		// Clean up other stuff!
	};
}
687493
def find_one(cls, *args, **kwargs):
        """"""
        database, collection = cls._collection_key.split('.')
        return current()[database][collection].find_one(*args, **kwargs)
817331
private Map<String, String[]> getShards(DBCollection collection) {
        DB config = collection.getDB().getSisterDB("config");
        DBCollection configShards = config.getCollection("shards");

        DBCursor cursorShards = configShards.find();

        Map<String, String[]> map = new HashMap<>();
        while (cursorShards.hasNext()) {
            DBObject currentShard = cursorShards.next();
            String currentHost = (String) currentShard.get("host");
            int slashIndex = currentHost.indexOf("/");
            if (slashIndex > 0) {
                map.put((String) currentShard.get(MONGO_DEFAULT_ID),
                        currentHost.substring(slashIndex + 1).split(","));
            }
        }
        return map;
    }
876632
function _find(collection, query, opts) {
  if (Tyr.logging.trace) {
    Tyr.trace({ e: 'db', c: collection.id, m: 'find', q: query });
    const cursor = collection.db.find(query, opts);
    //Tyr.Log.updateDuration(logPromise);
    return cursor;
  } else {
    return collection.db.find(query, opts);
  }
}
822155
def items_by_id(cls, ids, collection):
        
        col = cls.collection(collection)
        items = []
        base_url = urljoin(config.API_URL, 'collections/%s/items' % collection)
        for id in ids:
            try:
                items.append(Item(cls.query(urljoin(base_url, id))))
            except SatSearchError as err:
                pass
        return Items(items, collections=[col])
787716
def find(*args, &block)
      if block_given?
        decorated_collection.find(*args, &block)
      else
        ActiveSupport::Deprecation.warn('Using ActiveRecord\'s `find` on a CollectionDecorator is deprecated. ' +
                                        'Call `find` on a model, and then decorate the result', caller)

        decorate_item(object.find(*args))
      end
    end
141530
def find(self, *args, **kwargs):
        
        wrapper = kwargs.pop('wrapper', False)
        if wrapper is True:
            return self._wrapper_find(*args, **kwargs)

        return self.__collect.find(*args, **kwargs)
1202151
def user_list(user=None, password=None, host=None, port=None, database='admin', authdb=None):
    '''
    
    '''
    conn = _connect(user, password, host, port, authdb=authdb)
    if not conn:
        return 'Failed to connect to mongo database'

    try:
        log.info('Listing users')
        mdb = pymongo.database.Database(conn, database)

        output = []
        mongodb_version = _version(mdb)

        if _LooseVersion(mongodb_version) >= _LooseVersion('2.6'):
            for user in mdb.command('usersInfo')['users']:
                output.append(
                    {'user': user['user'],
                     'roles': user['roles']}
                )
        else:
            for user in mdb.system.users.find():
                output.append(
                    {'user': user['user'],
                     'readOnly': user.get('readOnly', 'None')}
                )
        return output

    except pymongo.errors.PyMongoError as err:
        log.error('Listing users failed with error: %s', err)
        return six.text_type(err)
184599
def _list_collections(self, sock_info, slave_okay, session,
                          read_preference, **kwargs):
        """"""

        coll = self.get_collection(
            "$cmd", read_preference=read_preference)
        if sock_info.max_wire_version > 2:
            cmd = SON([("listCollections", 1),
                       ("cursor", {})])
            cmd.update(kwargs)
            with self.__client._tmp_session(
                    session, close=False) as tmp_session:
                cursor = self._command(
                    sock_info, cmd, slave_okay,
                    read_preference=read_preference,
                    session=tmp_session)["cursor"]
                return CommandCursor(
                    coll,
                    cursor,
                    sock_info.address,
                    session=tmp_session,
                    explicit_session=session is not None)
        else:
            match = _INDEX_REGEX
            if "filter" in kwargs:
                match = {"$and": [_INDEX_REGEX, kwargs["filter"]]}
            dblen = len(self.name.encode("utf8") + b".")
            pipeline = [
                {"$project": {"name": {"$substr": ["$name", dblen, -1]},
                              "options": 1}},
                {"$match": match}
            ]
            cmd = SON([("aggregate", "system.namespaces"),
                       ("pipeline", pipeline),
                       ("cursor", kwargs.get("cursor", {}))])
            cursor = self._command(sock_info, cmd, slave_okay)["cursor"]
            return CommandCursor(coll, cursor, sock_info.address)
250120
def get_collection(self, collection, **kwargs):
        
        query = kwargs.get('query', {})
        projection = kwargs.get('projection', {})
        projection = None if len(projection) < 1 else projection
        limit = kwargs.get('limit', 0)  # no limit by default
        # sort = kwargs.get('sort', {})
        logging.info("About to get a collection from the database")
        logging.debug("Collection: {}".format(collection))
        logging.debug("Query: {}".format(query))
        logging.debug("Projection: {}".format(projection))
        logging.debug("Limit: {}".format(limit))
        records = \
            list(self.db[collection].find(query, projection).limit(limit))
        logging.debug("Got {} results".format(len(records)))
        return records