Learn R Programming

rmongodb (version 1.8.0)

mongo.update: Perform an update on a collection

Description

Perform an update on a collection.

Usage

mongo.update(mongo, ns, criteria, objNew, flags = 0L)

Arguments

mongo
(mongo) a mongo connection object.
ns
(string) namespace of the collection to which to update.
criteria
(mongo.bson) The criteria with which to match records that are to be updated.

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

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

objNew
(mongo.bson) The replacement object.

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

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

flags
(integer vector) A list of optional flags governing the operation:

Details

See http://www.mongodb.org/display/DOCS/Updating.

See Also

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

Examples

Run this code
mongo <- mongo.create()
if (mongo.is.connected(mongo)) {
    ns <- "test.people"

    buf <- mongo.bson.buffer.create()
    mongo.bson.buffer.append(buf, "name", "Joe")
    criteria <- mongo.bson.from.buffer(buf)

    buf <- mongo.bson.buffer.create()
    mongo.bson.buffer.start.object(buf, "$inc")
    mongo.bson.buffer.append(buf, "age", 1L)
    mongo.bson.buffer.finish.object(buf)
    objNew <- mongo.bson.from.buffer(buf)

    # increment the age field of the first record matching name "Joe"
    mongo.update(mongo, ns, criteria, objNew)

    buf <- mongo.bson.buffer.create()
    mongo.bson.buffer.append(buf, "name", "Jeff")
    criteria <- mongo.bson.from.buffer(buf)

    buf <- mongo.bson.buffer.create()
    mongo.bson.buffer.append(buf, "name", "Jeff")
    mongo.bson.buffer.append(buf, "age", 27L)
    objNew <- mongo.bson.from.buffer(buf)

    # update the entire record to { name: "Jeff", age: 27 }
    # where name equals "Jeff"
    # if such a record exists; otherwise, insert this as a new reord
    mongo.update(mongo, ns, criteria, objNew,
        mongo.update.upsert)

    # do a shorthand update:
    mongo.update(mongo, ns, list(name="John"), list(name="John", age=25))
}

Run the code above in your browser using DataLab