How i can find length of each item in a \"mol\"
list:
For example if I am looking for \"versionA\" : \"2.1.2\"
I expect ot get following result:
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"
}
}
}
}
}]
)
There is another way of doing it as well:
First you $map
each element of "mol", inside that you reduce each element of mol to the size of it's inside array using $reduce
.
db.stack.aggregate([
{
$match: { "versionA": "2.1.2" }
},
{
$project: {
_id: 0,
"project": 1,
"scene": 1,
mol: {
$map: {
input: "$mol",
as: "ob",
in: {
$reduce: {
input: "$$ob.data",
initialValue: 0,
in: { $add: ["$$value", 1] }
}
}
}
}
}
}
]);