mongoDB聚合 - 用动态键在对象中的值执行总和
假设我有以下集合,_id
和特质
。
[
{
_id: 1,
traits: {
Rarity: {
infoin: 15,
},
Type: {
iron: 3,
sliver: 5,
wood: 7,
},
},
},
{
_id: 2,
traits: {
Cloth: {
barron1: 11,
barron2: 12,
},
Hair: {
black: 6,
yellow: 9,
red: 8
}
},
},
...
]
如您所见,特征的键
是动态的,也是子对象的键。
这是我想得到的结果:
[
{
_id: 1,
traits: 15,
},
{
_id: 2,
traits: 23
}
]
提示:
infocoin =铁 + sliver +木材
barron1 + barron2 =黑色 +黄色 +红色
Let's say I have the following collection with _id
and traits
.
[
{
_id: 1,
traits: {
Rarity: {
infoin: 15,
},
Type: {
iron: 3,
sliver: 5,
wood: 7,
},
},
},
{
_id: 2,
traits: {
Cloth: {
barron1: 11,
barron2: 12,
},
Hair: {
black: 6,
yellow: 9,
red: 8
}
},
},
...
]
As you can see keys of traits
are dynamic and the keys of sub-objects as well.
Here is the result I wanna get:
[
{
_id: 1,
traits: 15,
},
{
_id: 2,
traits: 23
}
]
Tip:
infocoin = iron + sliver + wood
barron1 + barron2 = black + yellow + red
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$ set
- settraitobjs
数组字段通过通过$ objectToArray将对象转换为数组
。$ set
- setfirstTraitValues
字段通过从traitobjs
数组中获取第一个文档的值,然后通过$ objecttoaray 。
$ project
- 装饰输出文档。 SET特征
字段通过转换firstTraitValues
带有$ yrumend类型的数组
和$ sum
所有v
值。示例mongo playground
因为第一个密钥文档中的所有值和第二个关键文档和
特征是相同的,
因此上述方法仅在
特征
的第一个关键文档中总结了所有值。$set
- SettraitObjs
array field by converting the object to array via$objectToArray
.$set
- SetfirstTraitValues
field by getting the value of first document fromtraitObjs
array, then converting from object to array via$objectToArray
.$project
- Decorate the output document. Settraits
field by convertingfirstTraitValues
array to number type with$reduce
and$sum
all thev
values.Sample Mongo Playground
Since all the values in the first key document and the second key document of
traits
are the same,Hence the above approach just sums up all the values in the first key document of
traits
.这个答案确实与 @yong-shun的答案,但它构成了一个
“ $ project” $ project'< /代码>。我不知道这是否会更有效。
尝试一下 mongoplayground.net.net 。
This answer is really the same as @yong-shun's answer but it composes everthing into one
"$project"
. I don't know if it would be more efficient or not.Try it on mongoplayground.net.