原子地创建带有子文档的mongodb文档? [英] create mongodb document with subdocuments atomically?

查看:69
本文介绍了原子地创建带有子文档的mongodb文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我有个聪明的时刻.但是这是我在抓狂的情况下的情况;

我希望能够刮擦多台机器和内核.每个网站,我都有不同的Front页面,我会抓取(例如,我要在网站stackoverflow上拥有stackoverflow.com/questions/tagged/javascript和stackoverflow.com/questions/tagged/nodejs的页面).

每个Front上都可能有一个article,当我发现一篇文章时,如果网址未知,我想创建一个Article,如果知道的话,我想在article.discover中创建一个Front条目.如果Front是未知的,否则将我的FrontDiscovery插入适当的Front.

这是我的模式;

FrontDiscovery = new Schema({
    _id         :{ type:ObjectId, auto:true },
    date        :{ type: Date, default:Date.now},
    dims        :{ type: Object, default:null},
    pos         :{ type: Object, default:null}
});

Front = new Schema({
    _id         :{ type:ObjectId, auto:true },
    url         :{type:String}, //front
    found       :[ FrontDiscovery ]
});

Article = new Schema({
    _id         :{ type:ObjectId, auto:true },
    url         :{ type: String , index: { unique: true } },
    site        :{ type: String },
    discover:[ Front]
});

我认为我最终会遇到的问题是比赛条件.当两个求职者(并行)找到相同(未知之前)的文章并创建一个新文章时.是的,我在上面有一个唯一的索引,并且可以用这种方式进行处理-非常糟糕,恕我直言.

但让我们走得更远;当-无论出于何种原因-我的2个工作奔跑者同时刮擦同一条战线并且都注意到Front尚无任何条目并创建一个添加FrontDiscovery的新条目时,我将以相同Front的两个条目.

您采取什么策略来避免这种情况?分别为每个文档的findByIdAndUpdate和upsert:true?如果是这样,我怎么能只将某些内容推送到嵌入式文档集合中,而不同时覆盖其他所有内容,但是如果还没有创建默认值,那么仍要创建默认值?

感谢您为我提供正确的指导!我真的希望我能有个庞大的头脑..

解决方案

使用upsert=true更新可用于执行原子的插入或更新"( 解决方案

Update with upsert=true can be used to perform an atomic "insert or update" (http://docs.mongodb.org/manual/core/update/#update-operations-with-the-upsert-flag).

For instance if we want to make sure a document in Front collection with specific url is inserted exactly once, we could run something like:

db.Front.update(
    {url: 'http://example.com'},
    {$set: {
       url: 'http://example.com'},
       found: true
    }
)

Operations on a single document in MongoDB are always atomic. If you make updates that span over multiple documents, then no atomicity is guaranteed. In such cases, you can ask yourself: do I really need the operations to be atomic? If the answer is no, then you probably will find your way around working with potentially unconsistent data. If the answer is yes and you want to stick with MongoDB, check out the design pattern on Two Phase Commits.

这篇关于原子地创建带有子文档的mongodb文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆