Update of Embedded Array Object

28 views
Skip to first unread message

Mark

unread,
Apr 25, 2012, 6:39:22 AM4/25/12
to mongodb-user
Hi

I am trying to update an embedded array object within a document but
am having no success.

If I have the following structure:

[{name:Mark,pets:[{type:dog,name:'fido'},{type:'cat',name:'puss'}]},
{name:'John',pets:[{type:dog,name:'rex'}]}]

How can I change the name of Mark's dog?

I have tried positional operator stuff but no luck
e.g. t.update( {'name':'Mark',pets.type:'dog'}, {$set:{'pets.
$.name':'rover'}}

Using array positioning does work but I don't know the index e.g.
t.update( {'name':'Mark',pets.type:'dog'}, {$set:{'pets.
1.name':'rover'}}

Thanks

Marc

unread,
Apr 25, 2012, 11:53:38 AM4/25/12
to mongodb-user
The update statement that you provided should work:

> db.pets.save({name:'Mark',pets:[{type:'dog',name:'fido'},{type:'cat',name:'puss'}]})
> db.pets.save({name:'John',pets:[{type:'dog',name:'rex'}]})
> db.pets.find().pretty()
{
"_id" : ObjectId("4f981b7231eb8983025f1579"),
"name" : "Mark",
"pets" : [
{
"type" : "dog",
"name" : "fido"
},
{
"type" : "cat",
"name" : "puss"
}
]
}
{
"_id" : ObjectId("4f981b9131eb8983025f157a"),
"name" : "John",
"pets" : [
{
"type" : "dog",
"name" : "rex"
}
]
}
> db.pets.update({'name':'Mark',"pets.type":'dog'}, {$set:{'pets.$.name':'rover'}})
> db.pets.find().pretty()
{
"_id" : ObjectId("4f981b7231eb8983025f1579"),
"name" : "Mark",
"pets" : [
{
"name" : "rover",
"type" : "dog"
},
{
"type" : "cat",
"name" : "puss"
}
]
}
{
"_id" : ObjectId("4f981b9131eb8983025f157a"),
"name" : "John",
"pets" : [
{
"type" : "dog",
"name" : "rex"
}
]
}
>

The positional operator was introduced in version 1.4. Are you using
a really old version of Mongo? Have you checked for obvious things,
like typeos and capitalization?

If your update still does not work, please give the version of Mongo
that you are using and the exact steps that you take that fail to make
the update, and we will attempt to reproduce. Thanks.

copypastecoder

unread,
Apr 25, 2012, 7:42:36 PM4/25/12
to mongod...@googlegroups.com
Thanks for your post, i kept trying to update in so many different ways, and not understanding why somethings like {comments.votes...} wasn't recognized in an update. For some reason i glossed over the positional operator, and it's exactly what I needed.
Reply all
Reply to author
Forward
0 new messages