In MongoDB, you can append an element to an existing array using the $push
operator. Here’s an example:
db.collection.updateOne(
{ _id: ObjectId("123456789012345678901234") },
{ $push: { myArray: "newElement" } }
)
In this example, we are using the updateOne()
method to update a single document in the collection
. The first parameter is a query that identifies the document to update, and the second parameter is an update operation.
The update operation uses the $push
operator to append the string “newElement” to the myArray
field in the identified document. If the myArray
field doesn’t exist, MongoDB will create it and append the new element.
You can also append multiple elements to an array using $push
and the $each
modifier:
db.collection.updateOne(
{ _id: ObjectId("123456789012345678901234") },
{ $push: { myArray: { $each: ["newElement1", "newElement2"] } } }
)
In this example, we are using the $each
modifier to append two new elements to the myArray
field.
Additionally, you can also append elements to the beginning of an array using the $push
operator in conjunction with the $position
modifier:
db.collection.updateOne(
{ _id: ObjectId("123456789012345678901234") },
{ $push: { myArray: { $each: ["newElement"], $position: 0 } } }
)
In this example, we are using the $position
modifier to append the new element to the beginning of the myArray
field.
Overall, mastering array appending in MongoDB involves understanding how to use the $push
operator, along with its various modifiers, to append one or more elements to an existing array field in a document.