如何用数组替换mongodb集合中的字符串

时间:2017-01-26 06:14:36

标签: arrays mongodb mongodb-query

我的FoodRecord记录包含以下内容:

"_modifierRecords" : [
    "com.domain.data.REM.FoodModifierRecord:57919e6930049c15986e7c05"
    "com.domain.data.REM.FoodModifierRecord:57919e6930049c15986e7c06"
], 
"_discountModifierRecords" : [

], 
"_salesRecord" : "com.domain.data.REM.SalesRecord:57919e6930049c15986e7c01"

如果com.domain.data.REM.存在于上述3个字段中,我需要将com.domain.data.替换为var operations = []; db.FoodRecord.find().forEach(function(doc) { var operation = { updateOne: { filter: { '_id': doc._id }, update: { '$set': { '_salesRecord': doc._salesRecord.replace('com.domain.data.REM.SalesRecord:', 'com.domain.data.SalesRecord:'), '_modifierRecords.$' : doc._modifierRecords.$.replace('com.domain.data.REM.FoodModifierRecord:', 'com.domain.data.FoodModifierRecord:') } } } }; operations.push(operation); }) operations.push({ ordered: true, writeConcern: { w: "majority", wtimeout: 5000 } }) db.FoodRecord.bulkWrite(operations, { ordered : false });

这是我到目前为止,但我遇到了问题:

Spring MVC

1 个答案:

答案 0 :(得分:0)

这个解决方案似乎有效,但这可能不是最佳解决方案。

db.FoodRecord.find(/* your query */).forEach(function(e,i){
    var newArr = [];
    e._salesRecord.forEach(function(e,i) {
         newArr.push(e.replace('REM.SalesRecord','SalesRecord'));
    });
    e._salesRecord = newArr;
    newArr = [];
    e._modifierRecords.forEach(function(e,i) {
         newArr.push(e.replace('REM.FoodModifierRecord','FoodModifierRecord'));
    });
    e._modifierRecords = newArr;
    db.FoodRecord.save(e);
});