繁体   English   中英

MongoDB批量插入操作而不是For-Loop

[英]MongoDB Bulk Insert Operation instead of For-Loop

让我们考虑一个由NodeJSMongoDB构建的社交网络。
因此,如果用户创建新帖子,则应将其保存到他/她的关注者源中。

此操作的简单实现如下(简化):

var newPost="New Post";
//get list of followers of user 1
var listOfFollowers = followersCollection.find({u:"1"}); 

for(var i=0;i<listOfFollowers.length;i++){
    var followerId = listOfFollowers[i]._id;
    //insert new post of user 1 to every follower feed
    feedsCollection.insertOne(
       {ownerId:followerId,authorId:"1",content:newPost}
    ); 
}

当然,如果关注者人数众多,这会带来非常糟糕的表现。 如何用一个快速执行的MongoDB查询做到这一点?

插入许多阅读此文档,我想您会得到答案

MongoDB提供批量文档插入功能,请查看此链接-https://docs.mongodb.com/manual/reference/method/db.collection.initializeUnorderedBulkOp/

db.collection.initializeUnorderedBulkOp()它创建一个无序的操作列表,并且mongodb并行执行此列表,因此它速度很快,并且您无需在mongo处理它时特别注意性能。

对于有序插入,可以使用db.collection.initializeOrderedBulkOp()

例如

var newPost="New Post";
var bulk = db.followersCollection.initializeUnorderedBulkOp();
//get list of followers of user 1
var listOfFollowers = followersCollection.find({u:"1"}); 

for(var i=0;i<listOfFollowers.length;i++){
    var followerId = listOfFollowers[i]._id;
    //insert new post of user 1 to every follower feed
    bulk.insert( {ownerId:followerId,authorId:"1",content:newPost});
}
bulk.execute();

如果您使用的是Mongoose,请检查Mongoose文档是否相同。 在上面的示例中,我只是试图解释如何使用普通的MongoDB做到这一点。

检查一下:

var newPost="New Post";

//Object Array
var collection = []

//get list of followers of user 1
var listOfFollowers = followersCollection.find({u:"1"}); 

for(var i=0;i<listOfFollowers.length;i++){
    var followerId = listOfFollowers[i]._id;
    collection.push({ownerId:followerId,authorId:"1",content:newPost})
}
feedsCollection.insert(collection); //Or use insertMany()

您可以创建对象数组并立即将其插入。 检查文档: -https : //docs.mongodb.com/manual/reference/method/db.collection.insert/#insert-multiple-documents

即使这是对您的问题的简单答案,但如果collection数组具有大量元素,则可能仍然存在性能问题。 因此,处理此问题的最佳方法是使用触发器。 https://docs.mongodb.com/stitch/triggers/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM