delete elem from array in array of subdocuments

19 views
Skip to first unread message

Tim Arnold

unread,
Jul 26, 2016, 10:43:32 AM7/26/16
to mongodb-user
Given a collection of documents like this, I want to delete 'bored' state from member 'b'. 
Without knowing the array index of member b.

doc = {'_id': ObjectID(),
       'name': 'the_name',
       'location': 'the_location',
       'members': [{'membername': 'a',
                    'membernum': '13',
                    'states': ['hungry', 'tired', 'happy']},
                    
                    {'membername': 'b',
                    'membernum': '8',
                    'states': ['bored', 'glad']}]
      }
If I knew the array index, I would use the code below, but I don't know how to change that to a situation where I only know the member name.

doc.update({name:'the_name'},
           {"$unset": {"members.1.states.0": 1});
doc.update({name:'the_name'},
           {"$pull": {"members.1.states": null}});

Is it possible to delete a specific element from an array in an array of subdocuments?

thanks,
--Tim

William Hagan

unread,
Jul 26, 2016, 11:42:20 AM7/26/16
to mongodb-user
Use the "$" operator thus:

doc.update({name:'the_name'}, {"$unset": {"members.$.states.0": 1});

cheers

Tim Arnold

unread,
Jul 26, 2016, 12:09:56 PM7/26/16
to mongodb-user
thanks. I thought the members.$.states.0 would hit each member's first element of the states array, but I want to match a specific member (name='b'). Am I misunderstanding?
thanks,
--Tim

Tim Arnold

unread,
Jul 26, 2016, 1:03:19 PM7/26/16
to mongod...@googlegroups.com
I was misunderstanding. 
The '$' is a  placeholder for the first match of the update query document, so all you have to do is put the subdocument you want to match in the query, like this:

doc.update({name:'the_name', "members.name": "b"},
           {"$unset": {"members.$.states.0": 1});

thanks!
--Tim

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: https://docs.mongodb.com/manual/support/
---
You received this message because you are subscribed to a topic in the Google Groups "mongodb-user" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mongodb-user/_EqvjjYuo3E/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/ae6c17e6-a3d6-45c3-8a22-952c555e5dab%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages