-1

I have following example

{ username : 'Alex', tags: ['C#', 'Java', 'C++'] }

To get the length of tags array

db.users.aggregate(
[
  {
     $project: {
        tags_count: {$size: "$tags"}
     }
  }
]
)

But how to get the length when I have nested lists

{ username : 'Alex', tags: [['C#', 'Java', 'C++']] }


res = collection.aggregate([{
    "$match": query
},{
    "$project": {
      "_id": 0,
      "name": "$name",
      "a1":{"$properties.has_a":{"$slice":1}}, //Line #a1
    }
}])

I also tried changing Line #a1 as follows too:

res = collection.aggregate([{
    "$match": query
},{'$group':{'_id':{'a_list':{'$first':"$properties.has_a"}}}},{
    "$project": {
      "_id": 0,
      "name": "$name",
      "a1":{"$size":'$id.a_list'}, //Line #a1
    }
}])

But nothing is working as expected

Document:

{
  u'_id': ObjectId('54ddcd23f084a315hju481ea'),
  u'properties': [
      {u'start_time': datetime.datetime(2015, 2, 13, 0, 0)},
      {u'end_time': datetime.datetime(2015, 2, 13, 0, 0)},
      {u'status': u'APPROVAL'},
      {u'has_a': [
            ObjectId('54ddc9d6f084a517dfebdeff'),
            ObjectId('54ddc9dbf084a397dfebdf1a')
        ]
       }
      {u'has_b': [
            ObjectId('54ddf9d6f084a317dfebdeff'),
            ObjectId('54dhj9dbf084a317dfebdf1a')
        ]
       }
  ]
}

It may also happen that the has_a has empty list like [] .

1 Answer 1

2

As I said in the comments, an $unwind stage followed with a $project & $size will fix your problem:

[
   {
        $unwind : "$tags"
   },
   {
        $project: {
               tags_count: {$size: "$tags"}
        }
   }
]

gives me this document:

{
    tags_count: 3
}

This answers your new question:

[
    {
         $unwind : "$properties"
    },
    {
         $unwind : "$properties.has_a"
    },
    {
         $group: {
             _id: null,
             count: {
                 $sum: 1
             }
          }
    }
]

returns following:

{ count: 2}
Sign up to request clarification or add additional context in comments.

4 Comments

This is not working. My tags is a list of list of objectIds'. This code is returning me an empty list
@rkatkam objectIDs should work as well, post one of your documents
@rkatkam where is $unwind? And please post one of your documents
I posted the document. Please have a look because I din't find any solution yet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.