在所有文档的所有字段中应用大写字母(MongoDB-聚合) [英] Apply uppercase in all the fields of all documents (MongoDB - aggregate)
本文介绍了在所有文档的所有字段中应用大写字母(MongoDB-聚合)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的文件:
[
{
"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'
}
}
])
预期结果:
[
{
"one": "AAA",
"two": "BBB",
"three": "ABA"
},
{
"one": "DD",
"two": "CC",
}
]
推荐答案
请尝试以下操作:
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' } }])
参考: MongoDB聚合
这篇关于在所有文档的所有字段中应用大写字母(MongoDB-聚合)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文