rmongodb (version 1.8.0)

mongo.count: Count records in a collection

Description

Count the number of records in a collection that match a query See http://www.mongodb.org/display/DOCS/Indexes.

Usage

mongo.count(mongo, ns, query = mongo.bson.empty())

Arguments

mongo
(mongo) A mongo connection object.
ns
(string) The namespace of the collection in which to add count records.
query
mongo.bson The criteria with which to match records that are to be counted. The default of mongo.bson.empty() matches all records in the collection.

Alternately, query may be a list which will be converted to a mongo.bson object by mongo.bson.from.list().

Alternately, query may be a valid JSON character string which will be converted to a mongo.bson object by mongo.bson.from.JSON().

Value

(double) The number of matching records.

See Also

mongo.find, mongo.find.one, mongo.insert, mongo.update, mongo.remove, mongo, mongo.bson.

Examples

Run this code
mongo <- mongo.create()
if (mongo.is.connected(mongo)) {
    # Count the number of records in collection people of database test
    people.count <- mongo.count(mongo, "test.people")
    print("total people")
    print(people.count)

    buf <- mongo.bson.buffer.create()
    mongo.bson.buffer.append(buf, "age", 21L)
    query <- mongo.bson.from.buffer(buf)

    # Count the number of records in collection people of database test
    # where age == 21
    just.legal.count <- mongo.count(mongo, "test.people", query)
    print("people of age 21")
    print(just.legal.count)

    buf <- mongo.bson.buffer.create()
    mongo.bson.buffer.start.object(buf, "age")
    mongo.bson.buffer.append(buf, "$gte", 21L)
    mongo.bson.buffer.finish.object(buf)
    query <- mongo.bson.from.buffer(buf)

    # Count the number of records in collection people of database test
    # where age >= 21
    total.legal.count <- mongo.count(mongo, "test.people", query)
    print("people of age 21 or greater")
    print(total.legal.count)

    # shorthand using a list:
    ford.count <- mongo.count(mongo, "test.cars", list(make="Ford"))
}

Run the code above in your browser using DataLab