下面是我的sails.js应用程序中支持自定义选择列表字段的结构(在此示例中)。总体思路是,我们支持在应用程序内的任何模型上收集自定义选择列表值,并且客户可以完全控制自定义字段的配置。
我使用这种关系模型,因为在更新每个自定义选择列表值时,使用简单的json字段缺乏健壮性。如果我允许客户将“内部”更改为“外部”,则需要使用新值更新针对该自定义选择列表记录的具有“内部”值的所有记录。
这样-当我更新CustomPicklistValue
通过ID引用该记录的任何地方的“值”字段时,它将使用新值。
现在,当我需要将此模型集成到我现有的报表引擎中时,问题就来了。
rawCollection
.aggregate(
[
{
$match: {
createdAt: {
$gte: rangeEndDate,
$lte: rangeStartDate
},
...$match
}
},
{
$project: {
...$project,
total: $projectAggregation
}
},
{
$group: {
_id: {
...$groupKey
},
total: {
[`$${aggrAttrFunc}`]: "$total"
}
}
}
],
{
cursor: {
batchSize: 100
}
}
)
Here is the main part of a method for retrieving and aggregating any models stored in my mongodb instance. A user can specify a whole range of things including but not limited to the model, field specific date ranges and filters such as "where certificate status equals expired" etc.
So I'm now presented with this data structure:
{
id: '5e5fb732a9422a001146509f',
customPicklistValues: [
{
id: '5e4e904f16ab94bff1a324a0',
value: 'Internal',
fieldName: 'Business Group',
customPicklist: '109c7a1a9d00b664f2ee7827'
},
{
id: '5e4e904f16ab94bff1a324a4',
value: 'Slack',
fieldName: 'Application',
customPicklist: '109c5a1a9d00b664f2ee7827'
}
],
}
And for the life of me can't work out if there's any way I can essentially pull out fieldName
and value
for each of the populated records as key-value pairs and add each to the parent record before running my match clause...
I think I need to use lookup to initially populate the customPicklistValues
and then merge them somehow?
Any help appreciated.
EDIT:
@whoami建议我使用$ addFields。在$ addFields填充链接记录之前,我需要做很多工作(由于Sails.js的Waterline如何处理将相关集合中的Mongo ObjectID保存为字符串),您可以在指南针中看到我的步骤:
最后一步是编辑它或在其中添加一个阶段,以实际上能够像Business Group: "Finance"
本示例中那样支持key:value对。
您可以在阶段结束后尝试以下阶段$lookup
:
db.collection.aggregate([
{
$addFields: {
customPicklistValues:
{
$arrayToObject: {
$map: {
input: '$customPicklistValues',
in: { k: '$$this.fieldName', v: '$$this.value' }
}
}
}
}
},
{ $replaceRoot: { newRoot: { $mergeObjects: ['$customPicklistValues', '$$ROOT'] } } },
{ $project: { customPicklistValues: 0 } }
])
测试: MongoDB-操场
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句