Upserts with clause

1 view
Skip to first unread message

Petrus

unread,
Sep 24, 2010, 9:09:25 AM9/24/10
to mongodb-user
Hi,

Given the following document structure: {key:1, timestamp:
1285330185411, data:"the important stuff"}, where the timestamp
indicates the time when the data was valid.

I want to generate an atomic upsert which:
1. insert the document if the key does not exist
2. does nothing if a document with the key exists, but the
existing timestamp i newer.
3 updates the document if a document with the key exists and the
existing timestamp is older.

Here are some initial attempts that (obviously) does not work:
- This update does not apply to requirement 2:
db.col.update({key:1}, {key:1, timestamp:1285330185411,
data:"some new info"}, true)

- This update tries to take into account the "newer-feature", but
actually inserts a duplicate in case 2
db.col.update({key:1, timestamp:{"$gte":1285315416000}}, {key:1,
timestamp:1285330185411, data:"some new info"}, true)

Does anyone know if this is possible in MongoDb and how to do it?

Rgds, Petrus


Eliot Horowitz

unread,
Sep 24, 2010, 10:41:27 AM9/24/10
to mongod...@googlegroups.com
If you put an unique index on key - then your 2nd example will work
since the insert will fail.

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> 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.
>
>

Petrus

unread,
Sep 27, 2010, 8:41:28 AM9/27/10
to mongodb-user
Thank you very much. That did the trick :). Also the updates preformed
much better when indexing the key.
But does the failure cost much in terms of performance. It seem that
the upserts run 10 times slower if exception occurs every time
compared to when it never occurs... I see there are some logging on
the MongoDb-server when this occurs, so that explains some of the
poorer performance...

Rgds Petrus
> > For more options, visit this group athttp://groups.google.com/group/mongodb-user?hl=en.- Hide quoted text -
>
> - Show quoted text -
Reply all
Reply to author
Forward
0 new messages