Apply uppercase in all the fields of all documents (MongoDB - aggregate)

假装没事ソ 提交于 2020-02-05 04:25:07

问题


Suppose that I have documents like these:

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

Is there a way (with aggregate) to apply a function to every field? Like this?

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

Expected result :

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

回答1:


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



来源:https://stackoverflow.com/questions/59906392/apply-uppercase-in-all-the-fields-of-all-documents-mongodb-aggregate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!