问题
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