Performing Data Cleanup In Mongodb Performing Data Cleanup In Mongodb mongodb mongodb

Performing Data Cleanup In Mongodb


Update

You can run the merge command from upcoming 4.4 version which allows updating the same collection the aggregation is running on. Pass the array as old location and new location

db.collection.aggregate([  {"$match":{"location":{"$in":[oldLocation,newLocation]}}},  {"$addFields":{"sortOrder":{"$indexOfArray":[[oldLocation,newLocation],"$location"]}}},  {"$sort":{"sortOrder":1}},  {"$group":{    "_id":null,    "oldLocationDoc":{"$first":"$$ROOT"},    "newLocationDoc":{"$last":"$$ROOT"}  }},  {"$addFields":{    "oldLocationDoc.old":{      "$filter":{        "input":"$oldLocationDoc.old",        "cond":{"$ne":["$$this",oldLocation]}      }    },    "newLocationDoc.new":{"$concatArrays":["$newLocationDoc.new",[newLocation]]}  }},  {"$project":{"locations":["$oldLocationDoc","$newLocationDoc"]}},  {"$unwind":"$locations"},  {"$replaceRoot":{"newRoot":"$locations"}},  {"$merge":{    "into":{"db":"db","coll":"collection"},    "on":"_id",    "whenMatched":"merge",    "whenNotMatched":"failed"  }}]

Original

Not possible to move array/field value from one document to another document in a single update operation.

You would want to use transactions to perform multi document updates in a atomic way. Requires replica set.

var session = db.getMongo().startSession();var collection = session.getDatabase('test').getCollection('collection');session.startTransaction({readConcern: {level:'snapshot'},writeConcern: {w:'majority'}});collection.update({location:oldLocation},{$pull:{availiblePurchaseIds:lastPurchaseId}});collection.update({location:newLocation},{$push:{enroutePurchaseIds:lastPurchaseId}});session.commitTransaction()session.endSession()

Other options would be to perform bulk updates in case of standalone mongod instance.

var bulk = db.getCollection('collection').initializeUnorderedBulkOp();bulk.find({location:oldLocation}).updateOne({$pull:{availiblePurchaseIds:lastPurchaseId}});bulk.find({location:newLocation}).updateOne({$push:{enroutePurchaseIds:lastPurchaseId}});  bulk.execute();


Are you moving the entire document from one collection to another or just moving the document's id? I can't help much with coffeescript but if you're looking to move entire documents you might find the following thread helpful.

mongodb move documents from one collection to another collection