Mongodb 如何快速缓存引用对象的文档计数?
我正在缓存引用文档的数量,发现我的方法太慢了 假设一个简单的一对多模型,带有针对帖子的注释。我插入了一些如下所示的内容:Mongodb 如何快速缓存引用对象的文档计数?,mongodb,Mongodb,我正在缓存引用文档的数量,发现我的方法太慢了 假设一个简单的一对多模型,带有针对帖子的注释。我插入了一些如下所示的内容: db.posts.insert( { _id:"foo", ncomments:0 } ); db.posts.insert( { _id:"bar", ncomments:0 } ); db.posts.insert( { _id:"baz", ncomments:0 } ); db.comments.insert( { post_id:"foo", comment:"F
db.posts.insert( { _id:"foo", ncomments:0 } );
db.posts.insert( { _id:"bar", ncomments:0 } );
db.posts.insert( { _id:"baz", ncomments:0 } );
db.comments.insert( { post_id:"foo", comment:"First comment" } );
db.comments.insert( { post_id:"foo", comment:"Second comment" } );
db.comments.insert( { post_id:"bar", comment:"Another comment" } );
现在,要重建所有ncomments字段,我需要执行以下操作:
db.posts.find().forEach( function(post){
var n = db.comments.find( { post_id: post._id } ).count();
db.posts.update( { _id: post._id }, { $set : { ncomments: n } } );
} );
在收集量变大之前,这种方法可以很好地工作——每1000个文档大约需要一秒钟的时间
有没有更快的方法来实现这一点,也许没有迭代脚本方法
我不是在问我应该如何组织数据;也不知道如何立即使缓存的较小部分无效。我在问,在给定的情况下,有什么更好的方法来实现这一点 我已经通过以下方法将这个过程加快了大约十倍
// allow application to reduce subset of posts if possible
var query = {};
// index all comment counts by post
var counts = {};
db.comments.aggregate( [
{ $match: query },
{ $group : {
'_id' : '$post_id',
'num' : { $sum: 1 }
} }
] ).forEach( function( group ){
counts[ group._id ] = group.num;
} );
// for all posts (including those without comments) \
// collect a multi-update batch
var updates = db.posts.initializeUnorderedBulkOp();
db.posts.find( query, { _id:1 } ).forEach( function( post ){
updates.find( { _id: post._id } ).update( { $set: {
ncomments: counts[ post._id ] || 0
} } );
} );
// execute all updates with a loose write concern for speed
updates.execute( { w: 0, j: false } );
在我接受自己的答案之前,我仍然愿意接受更好的答案