Count

Count records matching provided criteria. This function
is memory optimized version of find.

@param {String} connectionName
@param {String} collectionName
@param {Object} options
@param {Function} cb
499675
function (connectionName, collectionName, options, cb) {

      options = options || {};
      var connectionObject = connections[connectionName];
      var collection = connectionObject.collections[collectionName];

      // Find all matching documents
      collection.count(options, function (err, recordCount) {
        if (err) return cb(err);
        cb(null, recordCount);
      });
    }
612617
function get_database(Socket, DatabaseType) {
	return {

		//
		Count: function(Collection, Query, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter for Count.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'Count',
					query: Query
				},
				callback);
			return;
		},

		//
		Find: function(Collection, Query, Projection, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter for Find.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'Find',
					query: Query,
					projection: Projection
				},
				callback);
			return;
		},

		//
		FindOne: function(Collection, Query, Projection, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter for FindOne.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'FindOne',
					query: Query,
					projection: Projection
				},
				callback);
			return;
		},

		//
		Insert: function(Collection, Query, Options, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter Insert.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'Insert',
					query: Query,
					options: Options
				},
				callback);
			return;
		},

		//
		Remove: function(Collection, Query, Options, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter Remove.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'Remove',
					query: Query,
					options: Options
				},
				callback);
			return;
		},

		//
		RemoveAll: function(Collection, Options, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter for RemoveAll.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'RemoveAll',
					options: Options
				},
				callback);
			return;
		},

		//
		Update: function(Collection, Query, Update, Options, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter for Update.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'Update',
					query: Query,
					update: Update,
					options: Options
				},
				callback);
			return;
		}
	};
}
913644
public MongoCollection<Document> getCollection(String dbName, String collectionName) {
		return getDb(dbName).getCollection(collectionName);
	}
512043
public static boolean collectionExists(MongoDatabase db, String collectionName) {
        return db.listCollections().filter(Filters.eq("name", collectionName)).first() != null;
    }
173547
public function lastError($db, $cb, $params = [], $conn = null)
    {
        $e = explode('.', $db, 2);
        $params['getlasterror'] = 1;
        $cb = CallbackWrapper::wrap($cb);
        try {
            $this->request(
                self::OP_QUERY,
                pack('V', 0) . $e[0] . '.$cmd' . "\x00"
                . pack('VV', 0, -1) . bson_encode($params),
                true,
                $conn,
                function ($conn, $reqId = null) use ($db, $cb) {
                    if (!$conn) {
                        !$cb || $cb(['$err' => 'Connection error.']);
                        return;
                    }
                    $conn->requests[$reqId] = [$db, $cb, true];
                }
            );
        } catch (\MongoException $e) {
            Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
            if ($cb !== null) {
                $cb(['$err' => $e->getMessage()]);
            }
        }
    }
384557
function(connection, collection, definition, cb) {
      log.debug('define:', collection);

      // Create the collection and indexes
      connections[connection].createCollection(collection, definition, cb);
    }
997853
function(connection, collection, relations, cb) {
      log.debug('drop:', collection);
      // Add in logic here to delete a collection (e.g. DROP TABLE logic)

      return connections[connection].drop(collection, relations, cb);
    }
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);
  }
}
1185388
function (property, callback) {
        // if only one arg we count the collection
        if ([].slice.call(arguments).length === 1) {
            callback = property 
            property = 'key'
        } 
        var c = 0 
        this.each(function(e){
            if (e[property]) c++
        })
        this.fn('count', callback).call(this, c)
    }
916722
function (db, options, cb) {
	this.db = db;
	this.cb = cb;
	this.updateQueryMaker = options.update;
	this.insertQueryMaker = options.insert;
	this.maxUpdateAttemptsCount = options.maxUpdateAttemptsCount || 2;
	this.transform = options.transform;
	this.insertFirst = !!options.insertFirst;
	this.nonQuery = !!options.nonQuery;

	var self = this;
	this.updateAttemptsCount = 0;
	this.updateOrInsertBound = function () {
		self.updateOrInsert();
	};
}
204049
function(Collection, Query, callback) {
			if (typeof callback !== 'function') { throw Error('The callback function is a required parameter for Count.'); }
			do_database_call(Socket, DatabaseType, {
					collection: Collection,
					operation: 'Count',
					query: Query
				},
				callback);
			return;
		}
94858
public int count(Connection conn, Entity where) throws SQLException {
		checkConn(conn);
		
		final Query query = new Query(SqlUtil.buildConditions(where), where.getTableName());
		PreparedStatement ps = null;
		try {
			ps = dialect.psForCount(conn, query);
			return SqlExecutor.query(ps, new NumberHandler()).intValue();
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}
1277736
function (connectionName, collectionName, relations, cb) {

      var connectionObject = connections[connectionName];
      if (!connectionObject) return cb(Errors.InvalidConnection);

      async.series(
        [
          // drop the main table
          function(cb) {

            var collection = connectionObject.collections[collectionName];
            if (!collection) return cb(Errors.CollectionNotRegistered);

            collection.dropTable(function(err) {
              // ignore "table does not exist" error
              if (err && err.code === 8704) return cb();
              if (err) return cb(err);
              cb();
            });
          },

          // drop relations
          function(cb) {
            // do it in parallel
            async.eachSeries(relations,
              function(item, cb) {

                var collection = connectionObject.collections[item];
                if (!collection) return cb(Errors.CollectionNotRegistered);

                collection.dropTable(function(err) {
                  // ignore "table does not exist" error
                  if (err && err.code === 8704) return cb();
                  if (err) return cb(err);
                  cb();
                });
              },
              function(err, results) {
                if (err) return cb(err);
                cb();
              }
            );
          }
        ],
        function(err, results) {
          if (err) return cb(err);
          cb();
        }
      );
    }
294484
function findDataSources(connections, dataSources, cb) {
  //Just Want The Data Source IDs.
  logger.debug("findDataSources", {dataSources: dataSources});
  var dataSourceIDsToUpdate = _.map(dataSources, function(dataSourceUpdateData) {
    return dataSourceUpdateData.error ? null : dataSourceUpdateData._id;
  });

  dataSourceIDsToUpdate = _.compact(dataSourceIDsToUpdate);

  //No Valid Data Sources To Update. No Need To Search For Data Sources
  if (dataSourceIDsToUpdate.length === 0) {
    return cb(undefined, dataSourceIDsToUpdate);
  }

  var query = {

  };

  //Searching By ID. Just one mongo call to get them all. More Efficient
  query[CONSTANTS.DATA_SOURCE_ID] = {
    "$in": dataSourceIDsToUpdate
  };

  lookUpDataSources(connections, {
    query: query
  }, function(err, foundDataSources) {
    if (err) {
      logger.error("Error Finding Data Sources ", {error: err});
      return cb(buildErrorResponse({
        error: err,
        userDetail: "Unexpected Error When Searching For A Data Source",
        code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
      }));
    }

    //Map Found Data Source Documents
    var dsWithDocuments = _.map(dataSources, function(validDataSource) {
      var matchingDocument = _.find(foundDataSources, function(dataSourceDocument) {
        return _.isEqual(dataSourceDocument._id.toString(), validDataSource._id.toString());
      });

      //If the document is found, assign it to the object, if not, set an error
      if (matchingDocument) {
        validDataSource.document = matchingDocument;
      } else {
        validDataSource.error = buildErrorResponse({
          error: new Error("Data Source Not Found"),
          userDetail: "Data Source Not Found",
          code: ERROR_CODES.FH_FORMS_NOT_FOUND
        });
      }

      return validDataSource;
    });

    var validInvalidDataSources = updateValidAndInvalidDataSources(dsWithDocuments, []);

    logger.debug("findDataSources", {validInvalidDataSources: validInvalidDataSources});

    cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid);
  });
}
1140224
function findByUsername(username, cb) {
  db.getClient(function(err, client, done) {
    client.query(SELECT_USERNAME, [username], function(err, r) {
      var result = r && r.rows[0];
      if(!err && !result) { err = new exceptions.NotFound(); }
      if(err) {
        cb(err);
        done(err);
      } else {
        cb(null, result);
        done();
      }
    });
  });
}
937704
function (connection, collections, cb) {

      if (!connection.identity) return cb(Errors.IdentityMissing);
      if (connections[connection.identity]) return cb(Errors.IdentityDuplicate);

      // Store the connection
      connections[connection.identity] = {
        config: connection,
        collections: collections,
        client: null
      };


      // connect to database
      new Connection(connection, function (err, client) {

        if (err) return cb(err);

        connections[connection.identity].client = client;

        // Build up a registry of collections
        Object.keys(collections).forEach(function (key) {
          connections[connection.identity].collections[key] = new Collection(collections[key], client);
        });

        // execute callback
        cb();
      });

    }
985720
public function countObjects(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
    {
        $partial = $this->collObjectsPartial && !$this->isNew();
        if (null === $this->collObjects || null !== $criteria || $partial) {
            if ($this->isNew() && null === $this->collObjects) {
                return 0;
            }

            if ($partial && !$criteria) {
                return count($this->getObjects());
            }

            $query = ChildObjectQuery::create(null, $criteria);
            if ($distinct) {
                $query->distinct();
            }

            return $query
                ->filterBySport($this)
                ->count($con);
        }

        return count($this->collObjects);
    }