복붙노트

[MONGODB] 몽구스 (MongoDB를) 일괄 삽입?

MONGODB

몽구스 (MongoDB를) 일괄 삽입?

지금합니까 몽구스 V3.6 +를 지원 일괄 삽입? 나는 몇 분 동안 검색 한하지만 해당 검색어와 일치하는 것도 오래된 몇 년이고 답은 명료 없음이었다.

편집하다:

미래 참고로, 대답은 () Model.create를 사용하는 것입니다. 당신이 배열로 삽입 할 문서를 전달할 수 있도록, 자사의 첫 번째 인수로 배열을 받아 ()를 만듭니다.

Model.create () 설명서를 참조하십시오

해결법

  1. ==============================

    1.Model.create ()는 매우 큰 일괄 처리하는 경우 삽입 할 수있는 나쁜 방법입니다. 그것은 매우 느려집니다. 이 경우 당신은 더 나은 수행 Model.collection.insert을 사용해야합니다. 대부분의 크기에 따라 Model.create는 ()도 충돌합니다! 백만 문서, 행운과 노력했다. Model.collection.insert 사용은 단 몇 초 걸렸습니다.

    Model.create ()는 매우 큰 일괄 처리하는 경우 삽입 할 수있는 나쁜 방법입니다. 그것은 매우 느려집니다. 이 경우 당신은 더 나은 수행 Model.collection.insert을 사용해야합니다. 대부분의 크기에 따라 Model.create는 ()도 충돌합니다! 백만 문서, 행운과 노력했다. Model.collection.insert 사용은 단 몇 초 걸렸습니다.

    Model.collection.insert(docs, options, callback)
    

    몽구스의 저자는 여기에 지적으로, 몽고 드라이버 직접 검증 절차 및 액세스 우회이 방법 것입니다. 이 트레이드 오프의 당신은 많은 양의 데이터를 처리하고 있기 때문에 확인해야합니다, 그렇지 않으면 당신은 (우리가 여기 문서 수십만 얘기 기억) 모두에서 데이터베이스에 삽입 할 수 없습니다.

    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년 6월 22일 업데이트 : 삽입 () 여전히 잘 사용할 수 있지만, 그것은 insertMany 찬성되지 됐어요 (). 그냥 드롭 인 교체로 사용할 수 있습니다 모든 것이 잘 작동합니다 그래서 매개 변수는 정확히 동일합니다 (물론, 반환 값은 약간의 차이가 있지만, 당신은 아마 어쨌든 그것을 사용하지 않는).

  2. ==============================

    2.모델 방법 .insertMany ()와 삽입 4.4.0 소개합니다 --true-- 대부분을 몽구스. 더 빠른 .create 루핑 () 또는 어레이와 함께 제공하는 대신 방법이다.

    모델 방법 .insertMany ()와 삽입 4.4.0 소개합니다 --true-- 대부분을 몽구스. 더 빠른 .create 루핑 () 또는 어레이와 함께 제공하는 대신 방법이다.

    용법:

    var rawDocuments = [/* ... */];
    
    Book.insertMany(rawDocuments)
        .then(function(mongooseDocuments) {
             /* ... */
        })
        .catch(function(err) {
            /* Error handling */
        });
    

    또는

    Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });
    

    당신은 그것을 추적 할 수 있습니다 :

  3. ==============================

    3.사실, 당신은 몽구스의 "생성"방법을 사용할 수 있습니다,이 예제를 참조 문서의 배열을 포함 할 수 있습니다 :

    사실, 당신은 몽구스의 "생성"방법을 사용할 수 있습니다,이 예제를 참조 문서의 배열을 포함 할 수 있습니다 :

    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.create의) Candy.collection.insert를 (사용하는 것 () - 위의 예에서 사용 - 더 빨리 때문에 (이 느린 그래서 () 각 항목에 () Model.save 호출 생성).

    자세한 내용은 몽고 문서를 참조하십시오 : http://docs.mongodb.org/manual/reference/method/db.collection.insert/

    (이 아웃 지적에 대한 arcseldon 덕분에)

  4. ==============================

    4.넌 배열에 값을 삽입하여 MongoDB의 쉘을 사용하는 일괄 삽입을 수행 할 수있다.

    넌 배열에 값을 삽입하여 MongoDB의 쉘을 사용하는 일괄 삽입을 수행 할 수있다.

    db.collection.insert([{values},{values},{values},{values}]);
    
  5. ==============================

    5.당신은 가장 높은 점수의 응답으로, 몽구스를 사용하여 삽입 대부분을 수행 할 수 있습니다. 그러나 작동하지 않을 수있는 예, 그것은해야한다 :

    당신은 가장 높은 점수의 응답으로, 몽구스를 사용하여 삽입 대부분을 수행 할 수 있습니다. 그러나 작동하지 않을 수있는 예, 그것은해야한다 :

    /* 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);
        }
    }
    

    벌크 삽입을위한 스키마 인스턴스를 사용하지 마십시오, 당신은 일반 맵 객체를 사용한다.

  6. ==============================

    6.사용하는 경우 몽구스를 사용하여, 1000 개 이상의 문서의 한계가 보인다

    사용하는 경우 몽구스를 사용하여, 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 문서를 테스트 할 때하지만이 빠른 속도로 거의 두 배입니다 :

    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);
        });
    }
    
  7. ==============================

    7.여기 insertMany와 저장 데이터를 저장하는 두 방법입니다

    여기 insertMany와 저장 데이터를 저장하는 두 방법입니다

    1) 몽구스 일괄 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) 몽구스 .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});
            })
        })
    })
    
  8. ==============================

    8.나는 동일을 달성하기 위해 비동기 대해 forEach (비동기 foreach는 NPM 패키지 문서에 대한 링크)를 사용했다.

    나는 동일을 달성하기 위해 비동기 대해 forEach (비동기 foreach는 NPM 패키지 문서에 대한 링크)를 사용했다.

    내 코드는 req.body의 문서를 받고 below.I 오전과 같다.

    var forEach = require('async-foreach').forEach;    
    exports.save_Ctrl = function (req, res) {    
    //  var l=req.body;
    //  console.log("length:",l.length);
    
     forEach(req.body, function(item, index, object,err) {
    
        console.log(req.body[index]);
        var post = new saveObj(req.body[index]);   
    
            //save model to MongoDB
        post.save(function (err) {
            if (err) {
                console.log('error saving :' + err.message);
                return err;
            }   
            else {
                console.log("Post saved");
            }
        });       
    
      });    
     }
    
  9. ==============================

    9.우리의 프로젝트에서 작업하고 관련 코드를 공유 :

    우리의 프로젝트에서 작업하고 관련 코드를 공유 :

    //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);
        });
    
  10. from https://stackoverflow.com/questions/16726330/mongoose-mongodb-batch-insert by cc-by-sa and MIT license