Roman
Roman

Reputation: 2175

Push element in any position of array in the subdocument

In MongoDB 2.6 we can use $position (http://docs.mongodb.org/master/reference/operator/update/position/) modifier to specifies the location in the array during update of an array in a document. But I would like to insert in an array in a subdocument.

Document schema:

{
  subdoc: {
    array: ['0', '1', '2', '5', '6']
  }
}

The following update pushes the elements in the end of array..

db.collection.update(
   { _id: tsId },
   {$push: { 'subdoc.array': { $each:['3', '4'], $position:3 } }});

So, the result is

{
  subdoc: {
    array: ['0', '1', '2', '5', '6', '3', '4']
  }
}

But I expect

{
  subdoc: {
    array: ['0', '1', '2', '3', '4', '5', '6']
  }
}

Is it possible in MongoDB 2.6?

Upvotes: 1

Views: 4678

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

It's a fair proposition in your question, however you basically have the concept wrong.

The first of which is that you have missed the concept that arrays in general have their entries starting at an index of 0 for the first element, so your "positioning" is out by one unit in this case and should have been:

db.collection.update(
   { _id: tsId },
   {$push: { 'subdoc.array': { "$each":["3", "4"], "$position": 3 } }}
)

And since you are now inserting at the correct position, then your elements are in the correct place.

Upvotes: 3

Related Questions