我有一个像下面这样的集合:
{
id: 1,
names: {
first: 'Ana',
second: '',
third: 'Smith',
four: 'Smitchd'
},
used: [
{
position: 'first',
id: 'A'
},
{
position: 'second',
id: 'B'
},
]
}
我需要used names
通过文档计算有多少集合,不包括那些是空的。
names
used的位置保存在一个名为 的数组中used
。
在示例中,我需要计算内部存在的名称used
,但 innames
不为空
我尝试使用reduce 遍历数组进行聚合used
,我可以计算数组中的项目,但我不能使用reduce 中的字段名称。
db.collection.aggregate([
{ $match: id: 1 },
{ $project: {
totalUsed: $reduce: {
input: '$used',
initialValue: 0,
in: { $add: ['$$value', { $cond: [{ $eq: ["$$name.$$this.position", '' ]}, 1, 0] }]}
}
}}
])
我 nedd 获得未使用空名称的计数...在示例中,我应该得到计数:1,因为即使在使用时存在 first 和 secodn,字段 names.second 也是空的。
我解决了...
我将对象names
转换为一个对象数组 ({ k: key, v: value }),然后我用names
(new array)声明了一个变量,used
并使用了一个 reduce insed。
我在新数组中寻找$$used.position
reduce中键的索引,然后比较值是否为“”,并根据情况添加1或0
db.collection.aggregate([
{ $match: id: 1 },
{
$project: {
id: "$id",
used: { "$used" },
names: { $objectToArray : "$names" },
}
},
{
$project: {
totalUsed: {
$let: {
vars: { names: "$names", used: "$used" },
in: {
$reduce: {
input: "$$used",
initialValue: 0,
in: {
$add: [
"$$value",
{
$cond: [
{ $eq: [{ $arrayElemAt: ["$$names.v", { $indexOfArray: ["$$names.k", "$$this.position"] } ]}, ""]},
0,
1
]
}
]
}
}
}
}
}
}
},
{
$group: { _id: "$id", used: { $sum:"$totalUsed" } }
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句