Update or Insert a list of objects

201 views
Skip to first unread message

bsr

unread,
May 9, 2011, 9:58:03 PM5/9/11
to mgo-users
Hello,

I have a list of objects I need to persist.

type Box struct {
Id, Width, Deapth, Height int
}

values = [{2, 20, 35, 50}, {3, 30, 20, 25}, {5, 40,20,10}]

The object id (2, 3 & 5 here) is unique in the collection. If the ID
is already present, I need to update the Width, Deapth, Height values
(or whiever changed), else needs to insert the new item.
I could not find much material on upsert, and not sure whether it is
mainly for incrementing counter values. Is there a better option than
the below flow

1. Iterate over the list
2. for each item, send a find request and check for existance
3. If no match, insert
4. Else, send an update requst with modified values

Is there a better way??


thank you
bsr.

Mike Ramirez

unread,
May 9, 2011, 10:41:51 PM5/9/11
to mgo-...@googlegroups.com
On Monday, May 09, 2011 06:58:03 PM bsr wrote:


> I could not find much material on upsert, and not sure whether it is
> mainly for incrementing counter values.


My understanding of Upsert is that it tries to update the row, if that fails,
insert the values. This is generically, the basic requirements of being an
upsert. Which seems to me to fit the description of Upsert in the mgo docs:

"Upsert finds a single document matching the provided selector document and
modifies it according to the change document. If no document matching the
selector is found, the change document is newly inserted instead."[1]


examples of upsert with mysql look like this:

INSERT INTO foo (a, b, c) VALUES(10, 20, 30) ON DUPLICATE KEY UPDATE
a = 10,
b = 20,
c = 30;


I think you might have been confused with the mongodb manual that shows
upserts with incrementing some counter. I think this was just a basic example
of upsert, because the updating page describes upsert as an argument to
Update() as this:

upsert - if this should be an "upsert"; that is, if the record does not exist,
insert it [2]

All this sounds like what you're doing and looking for.

Mike

[1] http://goneat.org/pkg/launchpad.net/mgo/#Collection.Upsert
[2] http://www.mongodb.org/display/DOCS/Updating#Updating-update%28%29
--
Life is like a sewer. What you get out of it depends on what you put into it.
-- Tom Lehrer

bsr

unread,
May 10, 2011, 6:44:20 AM5/10/11
to mgo-users
Thanks Mike for the detailed answer, I forgot to check mgo
documentation regarding this.. i will try this out.. thanks again.
Reply all
Reply to author
Forward
0 new messages