如何使用最佳实践有效地在MongoDB中插入一百万条用户记录的一百万条通知记录?



我有两个集合Users和Notifications。我有100万用户,我想为每个用户创建一个通知记录,所以我需要插入100万通知记录。使用MongoDB和nodejs有效地做到这一点的最佳实践是什么?我应该手动迭代用户,还是在MongoDB中有内置的实用程序来有效地做到这一点。

Usersschema:

{
"_id": "61b76dcef2d79f189f619daa",
"email": "test@test.com",
"name": "test"
}

Notificationsschema:

{
"_id": "61b76dcef2d79f189f610000",
"userID": "61b76dcef2d79f189f619daa", //this is ref to user
"data": "test data",
"isSeen": false
}

下面是一种使用一些"种子"创建notifications集合的方法。数据。

[MongoDB Atlas "Export Pipeline to Node"]

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
/*
* Requires the MongoDB Node.js Driver
* https://mongodb.github.io/node-mongodb-native
*/
const agg = [
{
'$project': {
'userId': '$_id', 
'data': 'test data', 
'isSeen': {
'$not': true
}
}
}, {
'$out': 'notifications'
}
];
MongoClient.connect(
'connection string',
{ useNewUrlParser: true, useUnifiedTopology: true },
function(connectErr, client) {
assert.equal(null, connectErr);
const coll = client.db('yourDatabase').collection('users');
coll.aggregate(agg, (cmdErr, result) => {
assert.equal(null, cmdErr);
});
client.close();
});

最新更新