mongodb aggregate to get length of first nested array/list

↘锁芯ラ 提交于 2019-12-13 08:56:39

问题


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:


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}


来源:https://stackoverflow.com/questions/28538982/mongodb-aggregate-to-get-length-of-first-nested-array-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!