Update
OneNode provides a flexible way to update documents in a collection using the same syntax as MongoDB's update functionality. You can use various update operators to modify fields, and optionally create new documents if no matches are found.
Basic Update Operation
The update
operation allows you to modify existing documents in a collection that match a specified filter. You can use different update operators like $set
, $inc
, $push
, and others to perform various modifications.
# Filter to match the document(s) to update
filter_criteria = {
"name": "Alice Smith"
}
# Update operations to apply
update_operations = {
"$set": {
"age": 30,
"email": "alice.smith@example.com"
},
"$inc": {
"login_count": 1
}
}
# Sending the request
response = collection.update(filter_criteria, update_operations)
Basic Update Response
A successful update operation will return a JSON response containing information about the operation's results:
{
"matched_count": 1,
"modified_count": 1,
"upserted_id": null
}
Upsert Operation
The upsert
parameter allows you to create a new document if no documents match the filter criteria. When set to true
, the operation will insert a new document with the specified update operations if no matches are found.
# Filter to match the document(s) to update
filter_criteria = {
"name": "Bob Johnson"
}
# Update operations to apply
update_operations = {
"$set": {
"age": 25,
"email": "bob.johnson@example.com",
"status": "active"
}
}
# Enable upsert to create document if no match is found
upsert = True
# Sending the request with upsert
response = collection.update(filter_criteria, update_operations, upsert)
Upsert Response
When a document is created via upsert, the response will include the upserted_id
of the new document as a MongoDB ObjectId:
{
"matched_count": 0,
"modified_count": 0,
"upserted_id": ObjectId("507f1f77bcf86cd799439011")
}
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
filter | Object | Yes | A query object to match the documents to update. For more details, refer to the filter operator syntax. |
update | Object | Yes | An object containing update operators that specify the modifications to apply. For more details, refer to the update operator syntax. |
upsert | Boolean | No | When set to true , creates a new document if no documents match the filter criteria. Defaults to false . |
Response Fields
Field | Type | Description |
---|---|---|
matched_count | Number | The number of documents that matched the filter criteria. |
modified_count | Number | The number of documents that were actually modified by the update operation. |
upserted_id | ObjectId | null | The MongoDB ObjectId of the document created during an upsert operation. Returns null if no document was upserted. |
How can we improve this documentation?
Share Your Thoughts
Your feedback helps us improve our documentation. Let us know what you think!