How to count items in list of lists

后端 未结 2 1753
南方客
南方客 2021-01-27 14:09

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:

相关标签:
2条回答
  • 2021-01-27 14:37

    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"
                        }
                    }
                }
            }
        }]
    )
    
    0 讨论(0)
  • 2021-01-27 14:37

    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] }  
                          }
                      }
                    }
                }
            }
        }
    ]);
    
    
    0 讨论(0)
提交回复
热议问题