Skip to main content

#db.u1(..)

Updates a single document in the database.

Similar to a MongoDB db.collection.updateOne(), with some syntax restrictions. It is generally more performant than #db.u(..), when needing to only update a single document.

Syntax

#db.u1(query, update)

Arguments

query

Selection filter for documents in the script owner's database. An empty query ( {} ) selects all documents.

Various MongoDB query operators can be used for conditional matching and other advanced querying functionality.

update

Can be either a document object (in which case all matches will be replaced by the new document), or an "update document" containing MongoDB update operators.

Update operators can be used to set new individual values, increment integer values atomically, pop and push to arrays, and more. For a comprehensive list, please see MongoDB's update operator documentation above.

Return Data

An object is returned upon updating documents with this function, providing extra details about whether it succeeded:

KeyInformation
nNumber of documents matched in the query. This will only ever be 0 or 1
nModifiedNumber of documents modified, after evaluating all update expressions. This will only ever be 0 or 1
okIf the operation succeeded, == 1
opTimeObject that contains a property 't' -- time of update operation in millieconds

Example

function(context, args) {
/*
where the database already contains documents:
#db.i(
{type:"my_data", my_key:"foo"},
{type:"my_data", my_key:"bar"}
)
*/
#db.u1({type:"my_data"}, { $set:{a_new_key:11} })

return #db.f({type:"my_data"}).array() // [{type:"my_data", my_key:"foo", a_new_key:11}, {type:"my_data", my_key:"bar"}]
}