$position

The `$position` operator is used to specify the position in the array where a new element should be inserted. This operator is useful when you need to insert an element at a specific index in an array rather than appending it to the end.

Syntax

{
  $push: {
    <arrayField>: {
      $each: [<value1>, <value2>],
      $position: <index>
    }
  }
}

Parameters

<arrayField>stringrequired

The field in the document that contains the array to be updated.

<value1>, <value2>, ...stringrequired

The values to be inserted into the array.

<index>numberrequired

The position at which the values should be inserted.

Examples

Sample Data

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "name": "Store Name",
  "tag": [
    "#ShopLocal",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

Insert an element at specific index location in an array field

Inserts the tag #NewArrival at the second position (index 1) in the tag array.

Query:

db.stores.update({
  _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
  $push: {
    tag: {
      $each: ["#NewArrival"],
      $position: 1
    }
  }
})

Output:

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "tag": [
    "#ShopLocal",
    "#NewArrival",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

Related