如何在mongo查询中获取子数组的长度

问题描述

以下是示例数据:

db.infos.find()
{
    "groupId": "1111","customerId": "A100","tracks": [{
        "trackId": "234","infos": [{
                "location": {
                    "address": "street1","city": "test","country": "US"
                }
            },{
                "location": {
                    "address": "street2",{
                "location": {
                    "address": "street3","country": "US"
                }
            }
        ]
    }]
}
{
    "groupId": "2222","tracks": [{
        "trackId": "345","infos": [{
                "location": {
                    "address": "street4",{
                "location": {
                    "address": "street5","tracks": [{
        "trackId": "666","country": "US"
                }
            }
        ]
    }]
}

我们需要一个查询获取 groupId 级别的“infos”子数组的长度。在上面的示例数据中,我们需要以下输出: 1111,3 2222,6

在下面尝试过,但不起作用:

 db.infos.aggregate([{"$project": {"groupId": "$groupId","samples": "$tracks.infos"}},{"$group": {"_id": "$groupId","samples": {"$push": "$samples"}}},{"$project": {"_id": 1,"samples": {"$size": "$samples"}}}],{   "allowdiskUse": true });

还有大量数据,上面的查询抛出一个 ExceededMemoryLimit 异常:

2021-07-10T07:20:14.415+0000 E QUERY    [js] Error: command Failed: {
    "ok" : 0,"errmsg" : "$push used too much memory and cannot spill to disk. Memory limit: 104857600 bytes","code" : 146,"codeName" : "ExceededMemoryLimit"
} : aggregate Failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:580:17
assert.commandWorked@src/mongo/shell/assert.js:673:16
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1074:12
@(shell):1:1

解决方法

这应该适用于放松:

db.collection.aggregate([
  {
    $unwind: "$tracks"
  },{
    $group: {
      "_id": "$groupId","count": {
        "$sum": {
          "$size": "$tracks.infos"
        }
      }
    }
  }
])

即使您的轨道阵列有多个对象,这也会将它们相加。 Playground

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...