3

How to realize count array in array using aggregate? I have this document structure:

{
    "_id" : 1,
    "link" : [ 
        {
            "linkHistory" : [ 
                {
                    "_id" : 1,
                }, 
                {
                    "_id" : 2,
                }
            ]
        }
    ]
}

and MongoDB code:

db.emailGroup.aggregate([
    {
        "$lookup": 
        {
            "from": "link",
            "localField": "_id",
            "foreignField": "emailGroupId",
            "as": "link"
        },
    },
    {
        "$unwind": "$link"
    },
    {
        "$match": {
            'link.originalLink': ""
        }
    },
    {
        "$group" : {
            _id: '$_id',
            link: {
                $push: '$link'
            }
        }
    }
])

I want to get count in other field for linkHistory. Is this possible?

nsc
  • 107
  • 1
  • 7
  • 1
    Not clear what you mean here? Count what? The inner array elements? `db.emailGroup.aggregate({ "$project": { "size": { "$sum": { "$map": { "input": "$link", "as": "l", "in": { "$size": "$$l.linkHistory" } } } } } })` Which would return `2` here. – Neil Lunn Jun 23 '17 at 09:39
  • It's working, thx – nsc Jun 23 '17 at 11:06
  • One more question - In $match I check if link.orginalLink is "", when link is not exist query return error "The argument to $size must be an array, but was was of type: missing". How can I change this to be good? – nsc Jul 03 '17 at 09:28
  • See [The argument to $size must be an Array, but was of type: EOO](https://stackoverflow.com/questions/24201120/mongodb-the-argument-to-size-must-be-an-array-but-was-of-type-eoo) – Neil Lunn Jul 03 '17 at 09:30
  • It's working, thx – nsc Jul 03 '17 at 10:04

0 Answers0