I’m a Mongo newbie, and trying to make this schema work.
Its intended for logging events as they happen on a high traffic website – just incrementing the number of times a certain action happens.
{
_id: "20110924",
Vals:[
{ Key: "SomeStat1": Value: 1},
{ Key: "SomeStat2": Value: 2},
{ Key: "SomeStat3": Value: 3}
]
}
,
{
_id: "20110925",
Vals:[
{ Key: "SomeStat1": Value: 3},
{ Key: "SomeStat8": Value: 13},
{ Key: "SomeStat134": Value: 63}
]
}, etc.
So _id here is the date, then an array of the different stats, and the number of times they’ve occurred. There may be no stats for that day, and the stat keys can be dynamic.
I’m looking for the most efficient way to achieve these updates, avoiding race conditions…so ideally all atomic.
I’ve got stuck when trying to do the $inc. When I specify that it should upsert, it tries to match the whole document as the conditional, and it fails on duplicate keys. Similarly for $addToSet – if I addToSet with { Key:”SomeStat1″ }, it won’t think it’s a duplicate as it’s matching against the entire document, and hence insert it alongside the existing SomeStat1 value.
What’s the best approach here? Is there a way to control how $addToSet matches? Or do I need a different schema?
Thanks in advance.
You’re using a bad schema, it’s impossible to do atomic updates on it. Do it like this:
or you can skip The
Valssubdocument and embed the stats in the main document.