Update Documents - Part 4
Learn and practice the $position, $slice, and $sort` operations while updating documents.
We'll cover the following...
We'll cover the following...
$position operator
We use the $position operator to add a value at the specific position.We can only use it with $each operator.
{
$push: {
<field>: {
$each: [
<value>,
...
],
$position: <numeric value>
}
}
}
The
$positionvalue indicates the value on the zero-based index.
- If the
$position= 0, it pushes the values e from the start of the array. - If the
$position> 0, it pushes the values from the provided index. - If the
$position< 0, it looks at the index from reverse order, then pushes the values.
First, let’s insert a task with an array field to show the use of the $position.
db.tasks.insertOne({name: "Learn MongoDB Topic 1",tags: ["new", "learning", "MongoDB"]});
Below is an example to insert tags ...