Updating an element in an embedded array?

75 views
Skip to first unread message

Russell Bateman

unread,
Jun 6, 2012, 11:13:41 AM6/6/12
to mongodb-user
I have a document with an embedded array (see full hierarchy below). The
array is a list of addresses; these are entities in Java (if that matters).

I wish to replace one of them with an updated address that will have the
same_id. I wonder if using $pull to rid myself of the one that's to
change, then using $push to, in effect, re-add it in its changed form is
the best way to do this. Or, is there a more intelligent way of doing
such an update?

Thanks,

Russ

{
"_id" : { "$oid" : "4fce8cca5a37d2376c78017f"},
"name" : "Jack",
"addresses" :
[
{
"_id" : { "$oid" : "4fce8cca5a37d2376c78017c"},
"type" : 1,
"street" : "123 My Street",
"city" : "Bedford Falls",
"state" : "NJ"
},
{
"_id" : { "$oid" : "4fce8cca5a37d2376c78017d"},
"type" : 2,
"street" : "456 My Street",
"city" : "Bedford Falls",
"state" : "NJ"
},
{
"_id" : { "$oid" : "4fce8cca5a37d2376c78017e"},
"type" : 3,
"street" : "789 My Street",
"city" : "Bedford Falls",
"state" : "NJ"
}
]
}

Jimmy McCarthy

unread,
Jun 6, 2012, 2:38:47 PM6/6/12
to mongodb-user
Is there a reason you can't use the $ positional operator (
http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator
)?

For example, you could run a query like:

collection.update({"_id":my_id, "addresses._id":my_address_id},
{"$set": {"addresses.$.street":my_new_street}})

if you wanted to just update the street for a specific address in a
specific object, or specify addresses.$.city and so on as well and
update the entire address in place. I'm not familiar with the Java
driver but this would be my method in the shell or python.

Russell Bateman

unread,
Jun 6, 2012, 3:39:37 PM6/6/12
to mongod...@googlegroups.com
Jimmy,

Thanks for replying and thanks especially for the code. I'll take a very
hard look at this.

There is no reason I can't do it right, I just suffer from a) being new
to this and b) not finding the Java documentation (a reference to which
you've given) sufficiently clear. I think doc tends to be written by
people who don't remember what it was like when they were SQL guys new
to Mongo and so don't remember what it was like to be totally confused.

My biggest challenge has been relating console/JS to Java with respect
to arrays, but I'm starting to get the hang of it. My second biggest
challenge has been to understand the doc in the first place on points
such as this one. The examples that turn up from Googling still tend to
be a bit too simple. That will change over time (for instance, I write
up and publish everything I learn in on-line notes I keep. Eventually,
those will come up in Google for others.)

And, I mean no offense: I wouldn't be abandoning MySQL/PostgreSQL if I
didn't think Mongo was hands-down the best invention since sliced bread.

Profuse thanks,

Russ
Reply all
Reply to author
Forward
0 new messages