$addToSet/$push to a given position of array

472 views
Skip to first unread message

Denis Andreev

unread,
Aug 22, 2011, 10:04:55 AM8/22/11
to mongodb-user
Suppose there is a collection of documents with array field like below
{
_id:1
Tags:["value1", "value3"]
}

New value e.g. "value2" needs to be added to the position 1 of array
like the result below
Tags:["value1", "value2", "value3"]
Or
Some existing array element needs to be updated in a specified
position.

Is there any way to add or update an array element in a specified
position of the array?

The same question with $pull operation.
Is there any way to remove an array element in a specified position of
array?

Scott Hernandez

unread,
Aug 22, 2011, 10:38:41 AM8/22/11
to mongod...@googlegroups.com
No, not really. You can use $set with an ordinal position but that
won't move things around like (I think) you want.

You probably want this: https://jira.mongodb.org/browse/SERVER-2363
(and the corresponding $pull one)

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

Sam Millman

unread,
Aug 22, 2011, 10:39:19 AM8/22/11
to mongod...@googlegroups.com
There is no way to add atm but there is a way to update:

update({ "Tags.1" => "value2"  })

There is a jira to be able to add items at a specific position:

Reply all
Reply to author
Forward
0 new messages