我在将测试文档插入 MongoDB 时遇到问题。
我正在使用 JavaScript 创建我的测试文档,然后通过 MongoDB Shell 运行它们。但我得到了一些意想不到的结果。
我的脚本创建了一个具有以下树结构的文档。
-Project
-Task
-Timesheet
当我尝试创建具有 15 个任务和 50 个时间表 ( createCollections("my project", 5, "my task", 15, 50, 100);
) 的 5 个项目时,我只会在数据库中获得 2 个完整(无错误)的文档。当我尝试创建具有 1 个任务和 5 个时间表 ( createCollections("my project", 5, "my task", 1, 5, 100);
) 的 5 个项目时,我只在数据库中获得 4 个完整(无错误)文档。比较奇葩。
我确信脚本会运行预期的迭代,因为我放置prints
以验证插入是否实际运行。
输出:(如预期的那样。)
before 0
after 0
before 1
after 1
before 2
after 2
before 3
after 3
before 4
after 4
剧本
db.test_embedded.drop();
db.createCollection("test_embedded");
var projectKey = 0;
var taskKey = 0;
var timesheetKey = 0;
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
function Iterator(array){
var i = 0;
this.array = array;
this.length = array.length;
this.next = next;
function next() {
return this.array[i++ % this.length];
}
}
var userIds = new Array();
db.users.find({},{_id:1}).forEach(function (user) { userIds.push(user._id) });
var projectCollaboratorSlice = 0;
function project(title) {
this._id = "project" + projectKey++;
this.title = title;
this.owner = userIds[0];
this.collaboraters = userIds.slice(projectCollaboratorSlice++ % userIds.length + 1);
this.tasks = new Array();
}
var taskCollaboratorSlice = 0;
function task(title) {
this._id = "task" + taskKey++;
this.title = title;
this.owner = userIds[0];
this.collaboraters = userIds.slice(taskCollaboratorSlice++ % userIds.length + 1);
this.timesheets = new Array();
}
var timesheetUserIter = new Iterator(userIds);
function timesheet(duration) {
this._id = "timesheet" + timesheetKey++;
this.owner = timesheetUserIter.next();
this.date = new Date(0);
this.duration = duration;
}
function createTimesheets(num, duration) {
var timesheets = new Array();
for (k = 0; k < num; k++) {
timesheets.push(new timesheet(duration));
}
return timesheets;
}
function createDoc(projectName, taskName, numTasks, numTimesheets, duration) {
var newProject = new project(projectName);
for (var i=0; i<numTasks; i++) {
var newTask = new task(taskName + i);
newTask.timesheets.push(createTimesheets(numTimesheets, duration));
newProject.tasks.push(newTask);
}
return newProject;
}
function createCollections(projectName, projectCount, taskName, taskCount, timesheetCount, timesheetDuration){
for (var p=0; p<projectCount; p++) {
print("before" + p);
db.test_embedded.insert(createDoc(projectName + p, taskName, taskCount, timesheetCount, timesheetDuration));
print("after" + p);
}
}
createCollections("my project", 5, "my task", 1, 5, 100);
是我的脚本造成的,还是对您可以通过脚本执行多少操作存在限制/错误?