首页 > 解决方案 > 在所有文档的所有字段中应用大写(MongoDB - 聚合)

问题描述

假设我有这样的文件:

[
  {
    "one": "aaa",
    "two": "bbb",
    "three": "aba"
  },
  {
    "one": "dd",
    "two": "cc",
  }
]

有没有办法(使用聚合)将函数应用于每个字段?像这样?

db.collection.aggregate([
{
   '$project': {
     'SOME FUNCTION TO UPPERCASE ALL THE FIELDS IN A ONCE'
    }
}
])

预期结果 :

[
  {
    "one": "AAA",
    "two": "BBB",
    "three": "ABA"
  },
  {
    "one": "DD",
    "two": "CC",
  }
]

标签: mongodbmongodb-queryaggregation-framework

解决方案


Please try this :

db.collection.aggregate([{
    /** Adding a new field data with required format */
    $addFields: {
        data: {
            $arrayToObject: { // Convert back to object (Executes as final step in this addFields)
                $map:
                {
                    input: { $objectToArray: "$$ROOT" }, // Convert each document's keys as k,v pairs 
                    as: "each",
                    /** Iterate over each document's keys & make values into upper case if k != _id */
                    in: { $cond: [{ $eq: ['$$each.k', '_id'] }, '$$each', { k: '$$each.k', v: { $toUpper: '$$each.v' } }] }
                }
            }
        }
    }
},
/** Replacing data as root document for each respective actual document  */
{ $replaceRoot: { newRoot: '$data' } }])

Test : MongoDB-Playground

Ref : MongoDB-aggregation


推荐阅读