How to upsert a document without overwriting existing fields?

780 views
Skip to first unread message

Sergey Schetinin

unread,
Oct 27, 2011, 5:09:03 PM10/27/11
to mongod...@googlegroups.com
Here's a use case: updating view count for a page and keeping a timestamp of the first view.

So I would do something like this: 

coll.update({'url': url}, {'first_viewed': now, '$inc': {'views': 1}}, upsert=True)

However, that would overwrite first_viewed for every update. Is there a modifier that is only applied when a document is new on upsert? Like 

coll.update({'url': url}, {'$if_new': {'first_viewed': now}, '$inc': {'views': 1}}, upsert=True)

Or possibly a modifier to set a field only if not present? Like this:

coll.update({'url': url}, {'$setdefault': {'first_viewed': now}, '$inc': {'views': 1}}, upsert=True)

Docs suggest there are none, but this seems like something a lot of people should have encountered before me.

Thanks.

-Sergey


Sam Millman

unread,
Oct 27, 2011, 5:28:11 PM10/27/11
to mongod...@googlegroups.com
Not really I just do a if statement and do one or the other or use activerecord to understand new record in client side etc.


--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To view this discussion on the web visit https://groups.google.com/d/msg/mongodb-user/-/sLs1LX4u2-kJ.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.

Sergey Schetinin

unread,
Oct 27, 2011, 5:35:14 PM10/27/11
to mongod...@googlegroups.com
Well, if there's no direct way to accomplish it, I recon one way to do it is to do an insert ignoring the getLastError (maybe getting the result just to be able to tell if the record is new) and then do an update. I'm not entirely sure this would be efficient. Another option is to do the upsert with the increment and check the document returned to see if the write-once property is present. If it's not, do another update setting that field.

However, it seems like it would not be too hard to support this more directly on the server side.

Scott Hernandez

unread,
Oct 27, 2011, 5:45:31 PM10/27/11
to mongod...@googlegroups.com

Sergey Schetinin

unread,
Oct 27, 2011, 5:52:07 PM10/27/11
to mongod...@googlegroups.com
Thanks!
Reply all
Reply to author
Forward
0 new messages