gpt4 book ai didi

mongodb动态项目汇总

转载 作者:行者123 更新时间:2023-12-04 10:07:09 26 4
gpt4 key购买 nike

我有我的结构集合

{ 
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
allowed: ['a', 'b']
}

在这个集合中,允许的数组存储要获取的字段名称。它由他想要获取的用户首选项设置,可以更改那些选定的字段,并在允许的数组中更新。

我想以某种方式使用 MongoDB 聚合和项目来获取允许的数组
无需手动列出 $project 中的所有字段
{ $project: { a: 1, b: 1 } }
我有一个解决方案,例如汇总使用以下项目
  db.getCollection("dummy").aggregate([
{ $match: {} },
{
$project: {
a: {
$cond: {
if: { $in: ["a", "$allowed"] },
then: "$a",
else: "$$REMOVE",
},
},
b: {
$cond: {
if: { $in: ["b", "$allowed"] },
then: "$b",
else: "$$REMOVE",
},
},
},
},
]);

但这也需要列出所有字段。我正在寻找一种替代解决方案,该解决方案可以在允许的数组中投影字段,而无需在 $project 中手动列出所有字段。

最佳答案

由于您不知道文档中的字段是什么,您必须将它们转换为 k - v配对使用 $objectToArray 然后使用 $filter 过滤掉不在 $allowed 中的字段大批。最终使用 $arrayToObject 以获得初始形状。

db.collection.aggregate([
{ $replaceRoot: {
newRoot: {
$arrayToObject: {
$filter: {
input: { $objectToArray: "$$ROOT" },
cond: { $in: ["$$this.k", "$allowed"] }
}
}
}
}}
])

MongoPlayground

关于mongodb动态项目汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61528576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com