我在将测试文档插入MongoDB时遇到了问题。
我正在使用JavaScripts创建我的测试文档,然后通过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);
这是我的脚本是原因还是有关于你可以通过脚本做多少的限制/错误?