Remove a item in nested array

1,209 views
Skip to first unread message

Zuyang Kou

unread,
Oct 13, 2011, 10:35:40 AM10/13/11
to mongod...@googlegroups.com
I have a document like this:

{'arr': [['Bob', true], ['Alice', true], ['Mike', false]]}

I want to remove the item containing 'Bob', after operation the
document will become {'arr': [['Alice', true], ['Mike', false]]} .

How can I do this?

Or I should choose another scheme?

--
Code is poetry.

Karl Seguin

unread,
Oct 13, 2011, 10:47:52 AM10/13/11
to mongod...@googlegroups.com

Zuyang Kou

unread,
Oct 13, 2011, 11:10:10 AM10/13/11
to mongod...@googlegroups.com
I don't know how to use $pull in this case, I trid db.foo.update({}, {
$pull : {'arr': {'0': 'Bob'}}}) , but take no effect.

Could you give me the exact command I should use?

On Thu, Oct 13, 2011 at 10:47 PM, Karl Seguin <karls...@gmail.com> wrote:
> Use $pull:
> http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
>
> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/mongodb-user/-/pAEypHYVje0J.
> 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.
>

--
Code is poetry.

Sam Millman

unread,
Oct 13, 2011, 11:40:46 AM10/13/11
to mongod...@googlegroups.com
It won't work on nested arrays.

The only way really atm is client side tbh.

Karl Seguin

unread,
Oct 13, 2011, 11:47:24 AM10/13/11
to mongod...@googlegroups.com
ya, sorry..I didn't pay close enough attention to your structure..my bad.

Brandon Diamond

unread,
Oct 13, 2011, 12:11:29 PM10/13/11
to mongodb-user
Hi Zuyang,

The best way forward is to change your schema such that you do not
have an array of arrays: instead, store a sub-document with two
fields, { "name": "Bob", "someNameForBool": true }.

Then, you can provide a matching expression so you can target sub-
documents by name. For example --

> db.stuff.save({ "arr": [ { "a": 1, "b": 2 }, { "a": 2, "b": 2 }, { "a": 3, "b": 1 } ] })
> db.stuff.update({}, { "$pull": { "arr": { "a": 2 } } })
> db.stuff.find()
{ "_id" : ObjectId("a0987e09ae70f987f"), "arr" : [ { "a" : 1, "b" :
2 }, { "a" : 3, "b" : 1 } ] }

Also, keep in mind that updates do not affect more than one document
by default. If more than one document will match your update selector,
you should pass in the multi-update flag.

Hope this helps,
- Brandon


On Oct 13, 11:10 am, Zuyang Kou <leaf...@gmail.com> wrote:
> I don't know how to use $pull in this case, I trid db.foo.update({}, {
> $pull : {'arr': {'0': 'Bob'}}}) , but take no effect.
>
> Could you give me the exact command I should use?
>
Reply all
Reply to author
Forward
0 new messages