Mongoose(mongodb) 배치 인서트?
현재 Mongoose v3.6+는 배치 삽입을 지원합니까?몇 분 동안 찾아봤지만 이 질문에 일치하는 것은 몇 년 된 것이고 대답은 분명히 '아니오'였다.
편집:
향후 참조를 위해서, 해답은 다음과 같습니다.Model.create()create()는 배열을 첫 번째 인수로 받아들이므로 문서를 배열로 삽입할 수 있습니다.
Model.create() 문서를 참조하십시오.
Model.create() vs Model.collection.insert(): 보다 빠른 접근법
Model.create()매우 큰 부피를 취급하고 있는 경우는, 인서트를 실시하는 것이 좋지 않습니다.아주 느릴 거예요.이 경우 다음 명령어를 사용해야 합니다.Model.collection.insert퍼포먼스가 훨씬 향상됩니다.부피의 크기에 따라Model.create()★★★★★★★★★★★★★★★★★★★★★!백만 건의 서류를 가지고 시도했지만, 잘 되지 않았어요.「」를 사용합니다.Model.collection.insert몇 초밖에 안 걸렸어요.
Model.collection.insert(docs, options, callback)
docs삽입할 문서의 배열입니다.options는 옵션 설정 오브젝트입니다.문서 참조callback(err, docs)모든 문서가 저장되거나 오류가 발생한 후 호출됩니다.문서
Mongoose의 저자가 여기서 지적한 바와 같이, 이 방법은 모든 검증 절차를 생략하고 Mongo 드라이버에 직접 액세스합니다.대량의 데이터를 처리하고 있기 때문에 이 문제는 타협해야 합니다.그렇지 않으면 데이터베이스에 데이터를 전혀 삽입할 수 없습니다(수십만 개의 문서가 있다는 것을 기억하십시오).
간단한 예
var Potato = mongoose.model('Potato', PotatoSchema);
var potatoBag = [/* a humongous amount of potato objects */];
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
업데이트 2019-06-22: 단insert()님은 아직 잘 사용할 수 있습니다.이거는 에 의해 폐지되었습니다.파라미터는 완전히 같기 때문에 드롭인 교환용으로만 사용할 수 있으며 모든 것이 정상적으로 동작합니다(반환값은 조금 다르지만 사용하지 않을 수 있습니다).
언급
Mongoose 4.4.0은 벌크 인서트를 지원하게 되었습니다.
4. 메서드 Mongoose 4.4.0을 했습니다..insertMany(). 핑보다inginginginginginginginging loop loop loop loop loop loop loop loop 보다 훨씬 .create()또는 어레이와 함께 제공합니다.
사용방법:
var rawDocuments = [/* ... */];
Book.insertMany(rawDocuments)
.then(function(mongooseDocuments) {
/* ... */
})
.catch(function(err) {
/* Error handling */
});
또는
Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });
추적할 수 있는 위치:
- https://github.com/Automattic/mongoose/issues/723
- https://github.com/Automattic/mongoose/blob/1887e72694829b62f4e3547283783cebbe66b46b/lib/model.js#L1774
실제로 Mongoose의 "작성" 방법을 사용할 수 있습니다. 문서 배열을 포함할 수 있습니다. 다음 예를 참조하십시오.
Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
});
콜백 기능에는 삽입된 문서가 포함됩니다.몇 개의 항목을 삽입해야 하는지 항상 알 수 있는 것은 아닙니다(상기와 같이 고정된 인수 길이).
var insertedDocs = [];
for (var i=1; i<arguments.length; ++i) {
insertedDocs.push(arguments[i]);
}
업데이트: 더 나은 솔루션
보다 나은 솔루션은Candy.collection.insert()대신Candy.create()- 위의 예에서 사용됨 - 더 빠르기 때문입니다(create()호출하고 있다Model.save()각 항목마다 더 느립니다.)
상세한 것에 대하여는, 다음의 Mongo 문서를 참조해 주세요.http://docs.mongodb.org/manual/reference/method/db.collection.insert/
(이 점을 지적해 준 arcseldon 덕분에)
다음은 insert Many와 save를 사용하여 데이터를 저장하는 방법입니다.
1) Mongoose 문서 배열 저장:insertMany대량으로
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const data = [/* array of object which data need to save in db */];
Potato.insertMany(data)
.then((result) => {
console.log("result ", result);
res.status(200).json({'success': 'new documents added!', 'data': result});
})
.catch(err => {
console.error("error ", err);
res.status(400).json({err});
});
})
2) Mongoose의 문서 배열 저장 방법:.save()
이 문서들은 병렬로 저장됩니다.
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const saveData = []
const data = [/* array of object which data need to save in db */];
data.map((i) => {
console.log(i)
var potato = new Potato(data[i])
potato.save()
.then((result) => {
console.log(result)
saveData.push(result)
if (saveData.length === data.length) {
res.status(200).json({'success': 'new documents added!', 'data': saveData});
}
})
.catch((err) => {
console.error(err)
res.status(500).json({err});
})
})
})
최고 점수 답변으로 mongoose를 사용하여 대량 삽입을 수행할 수 있습니다.그러나 이 예에서는 다음과 같이 동작할 수 없습니다.
/* a humongous amount of potatos */
var potatoBag = [{name:'potato1'}, {name:'potato2'}];
var Potato = mongoose.model('Potato', PotatoSchema);
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
벌크 삽입에는 스키마인스턴스를 사용하지 말고 플레인 맵개체를 사용해야 합니다.
mongoose를 사용하는 경우 1000개 이상의 문서 제한이 있는 것 같습니다.
Potato.collection.insert(potatoBag, onInsert);
다음을 사용할 수 있습니다.
var bulk = Model.collection.initializeOrderedBulkOp();
async.each(users, function (user, callback) {
bulk.insert(hash);
}, function (err) {
var bulkStart = Date.now();
bulk.execute(function(err, res){
if (err) console.log (" gameResult.js > err " , err);
console.log (" gameResult.js > BULK TIME " , Date.now() - bulkStart );
console.log (" gameResult.js > BULK INSERT " , res.nInserted)
});
});
그러나 10000개의 문서를 사용하여 테스트하는 경우 이 속도는 거의 2배 빨라집니다.
function fastInsert(arrOfResults) {
var startTime = Date.now();
var count = 0;
var c = Math.round( arrOfResults.length / 990);
var fakeArr = [];
fakeArr.length = c;
var docsSaved = 0
async.each(fakeArr, function (item, callback) {
var sliced = arrOfResults.slice(count, count+999);
sliced.length)
count = count +999;
if(sliced.length != 0 ){
GameResultModel.collection.insert(sliced, function (err, docs) {
docsSaved += docs.ops.length
callback();
});
}else {
callback()
}
}, function (err) {
console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved " , docsSaved, " DIFF TIME:",Date.now() - startTime);
});
}
배열에 값을 삽입하여 mongoDB 쉘을 사용하여 일괄 삽입을 수행할 수 있습니다.
db.collection.insert([{values},{values},{values},{values}]);
프로젝트 작업 코드 및 관련 코드 공유:
//documentsArray is the list of sampleCollection objects
sampleCollection.insertMany(documentsArray)
.then((res) => {
console.log("insert sampleCollection result ", res);
})
.catch(err => {
console.log("bulk insert sampleCollection error ", err);
});
언급URL : https://stackoverflow.com/questions/16726330/mongoose-mongodb-batch-insert
'programing' 카테고리의 다른 글
| Serde를 사용하여 커스텀 함수를 사용하여 옵션 필드를 역직렬화하려면 어떻게 해야 합니까? (0) | 2023.03.01 |
|---|---|
| jQuery AJAX 요청에 대한 응답으로 PNG 이미지 표시 (0) | 2023.03.01 |
| 최적의 문자열 연결/집약 방법 (0) | 2023.03.01 |
| AngularJS: 멀티파트 형식으로 심플한 파일 업로드를 구현하려면 어떻게 해야 합니까? (0) | 2023.03.01 |
| UI 라우터 확인 중 로드 스피너 적용 (0) | 2023.03.01 |