本文介绍了如何计算列表清单中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在"mol"
列表中找到每个项目的长度:
How i can find length of each item in a "mol"
list:
例如,如果我正在寻找"versionA" : "2.1.2"
,我希望获得以下结果:
For example if I am looking for "versionA" : "2.1.2"
I expect ot get following result:
{"project" : "A", "scene" : 13455312, mol:[3,2,1]},
{"project" : "B", "scene" : 13455344, mol:[3,3,3]}
我的数据:
{
"project" : "A",
"scene" : 13455312,
"versionA" : "2.1.2",
"versionB" : "2.1.9",
"mol" : [ {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}, {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }]}, {"data" : [ { "tran" : 'A' }]}]
},
{
"project" : "B",
"scene" : 13455344,
"versionA" : "2.1.2",
"versionB" : "2.1.9",
"mol" : [ {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}, {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}, {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}]
},
{
"project" : "C",
"scene" : 135555,
"versionA" : "2.1.3",
"versionB" : "2.1.9",
"mol" : [ {"data" : [ { "tran" : 'A' }]}, {"data" : [ { "tran" : 'A' }]}, {"data" : [ { "tran" : 'A' }]}]
}
推荐答案
您可以$match
到version
字段,然后$map
迭代mol
和$size
以计算数据字段的长度
You can $match
to the version
field and $map
which iterates the mol
and $size
to calculate the the length of data field.
db.collection.aggregate(
[{
$match: {
"versionA": "2.1.2"
}
}, {
$project: {
_id: 0,
"project": 1,
"scene": 1,
"mol": {
$map: {
input: "$mol",
as: "mo",
in: {
$size: "$$mo.data"
}
}
}
}
}]
)
这篇关于如何计算列表清单中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!