mongodb - 在所有文档的所有字段中应用大写(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",
}
]
解决方案
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
推荐阅读
- avro - GenericDatumWriter 的 Avro 压缩
- javascript - 使用 php 读取由 axios 发送的内容类型为:image/jpeg 的文件
- c# - .net 中的 DeserializeObject 仅适用于特定属性
- tensorflow - doc_controls 没有属性“可继承的标头”
- reactjs - 如何在反应三纤维画布内添加 jsx 组件?
- kubernetes - 如何使用 kubectl 删除超过 24 小时的机密?
- javascript - clearInterval 不清除函数内部的 setInterval
- javascript - 如何使用 javascript 将商品添加到购物车?
- c# - Microsoft 通用主机应用运行时配置:我真的需要在我的代码库中喷洒“IOptions<>”吗?
- node.js - 如何docker化复合节点js项目