Can you use $push on nested Arrays?

2,639 views
Skip to first unread message

Fernando A

unread,
Oct 18, 2011, 2:14:21 PM10/18/11
to mongodb-user
I was wondering if its possible to use $push to append entries to an
array that is nested 2 or 3 levels deep.

Marc

unread,
Oct 18, 2011, 4:01:04 PM10/18/11
to mongodb-user
The short answer is, "yes", but working with nested arrays gets
tricky. Here is an example:
> db.foo.save({_id: 1, a1:[{_a1id:1, a2:[{a2id:1, a3:[{a3id:1, a4:"data"}]}]}]})
> db.foo.find()
{ "_id" : 1, "a1" : [
{ "_a1id" : 1, "a2" : [
{ "a2id" : 1, "a3" : [
{ "a3id" : 1, "a4" : "data" }
] }
] }
] }
> db.foo.update({_id:1}, {$push:{"a1.0.a2.0.a3":{a3id:2, a4:"other data"}}})
> db.foo.find()
{ "_id" : 1, "a1" : [
{ "_a1id" : 1, "a2" : [
{ "a2id" : 1, "a3" : [
{ "a3id" : 1, "a4" : "data" }, { "a3id" : 2, "a4" :
"other data" }
] }
] }
] }

If you are unsure where one of your sub-documents lies within an
array, you may use one positional operator, and Mongo will update the
first sub-document which matches. For example:

> db.foo.update({_id:1, "a1.a2.a2id":1}, {$push:{"a1.0.a2.$.a3":{a3id:2, a4:"other data"}}})

> db.foo.find()
{ "_id" : 1, "a1" : [
{ "_a1id" : 1, "a2" : [
{ "a2id" : 1, "a3" : [
{ "a3id" : 1, "a4" : "data" }, { "a3id" : 2, "a4" :
"other data" }
] }
] }
] }

However, MongoDB does not support multiple positional operators or
wildcards. For example, the following will not work:

> db.foo.update({_id:1, "a1.a1id":1, "a1.a2.a2id":1}, {$push:{"a1.$.a2.$.a3":{a3id:2, a4:"other data"}}}) // DOES NOT WORK.

Here is a link to the Mongo Documentation on dot notation
http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)

Here is a link to the "$ positional operator" section of the Mongo
Document on Updating
http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

Additionally, many users have asked similar questions in the past. A
search of the Google Groups page for "nested arrays" returns some
similar threads, which may be relevant.
http://groups.google.com/group/mongodb-user/search?group=mongodb-user&q=nested+arrays&qt_g=Search+this+group

Hopefully the above will help you with what you were hoping to
accomplish with MongoDb. Good Luck!
Reply all
Reply to author
Forward
0 new messages