1

I've got collection of items,

[
    {
        itemId: 1249,
        someField: 'abc'
    },
    {
        itemId: 1479,
        anotherField: 'bcc'
    }
    ,
    // etc
]

I recieve another portion of data. Some of the items could already be there, some not,

[
    {
        itemId: 6534,
        someField: 'trw'
    },
    // already stored in collection..
    {
        itemId: 1249,
        someField: 'abc'
    }
]

I'm looking for the way of bulk insert of this data with upsert strategy (means, if item with such itemId is already there - update, otherwise insert).

Is that possible to do with only one query, of I need to go throught collection manually and upsert each item?

1 Answer 1

1

I use this, probably not the most effecent method, but it works

MongoClient.connect("mongodb://localhost:27017/devbed", {native_parser:true}, function(err, db) {
    db.collection(project.name).findOne({"revision":project.tmprev}, function(err,item){
                        if(item){
                          db.collection(project.name).update({JSON},{w:1},function(err, object) {
                              if (err) {console.warn(err.message);}
                              else {console.log("succesfully saved");
                              db.close();}
                          });
                        }
                        else{
                            db.collection(project.name).insert({JSON}]},{w:1},function(err, object) {
                            if (err) {console.warn(err.message);}
                            else {console.log("succesfully saved");
                            db.close();}
                            });
                        }

                    });
});

Wraping this in a function should work

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.