mongodb – Can I copy, modify and immediately paste a pair of records with 1 query?

Question:

Is it possible in mongodb to copy a couple of records, change some fields, and immediately paste the revised records? And all this with 1 request.

Answer:

Try this:

db.SomeCollection.find(SomeCriteria).forEach(function(clone){
    //меняем произвольные поля
    clone.num=clone.num+1; //числовое
    clone.str=clone.str+"2"; //строковое

    delete clone._id; //затираем старый id
    db.SomeCollection.insert(clone);
});

SomeCollection and SomeCriteria are the name of the collection and the required criteria. elem – the entry to be cloned

Scroll to Top