mongodb - 如何在mongo查询中获取子数组的长度
问题描述
以下是样本数据:
db.infos.find()
{
"groupId": "1111",
"customerId": "A100",
"tracks": [{
"trackId": "234",
"infos": [{
"location": {
"address": "street1",
"city": "test",
"country": "US"
}
},
{
"location": {
"address": "street2",
"city": "test",
"country": "US"
}
},
{
"location": {
"address": "street3",
"city": "test",
"country": "US"
}
}
]
}]
}
{
"groupId": "2222",
"customerId": "A100",
"tracks": [{
"trackId": "345",
"infos": [{
"location": {
"address": "street4",
"city": "test",
"country": "US"
}
},
{
"location": {
"address": "street5",
"city": "test",
"country": "US"
}
},
{
"location": {
"address": "street5",
"city": "test",
"country": "US"
}
}
]
}]
}
{
"groupId": "2222",
"customerId": "A100",
"tracks": [{
"trackId": "666",
"infos": [{
"location": {
"address": "street4",
"city": "test",
"country": "US"
}
},
{
"location": {
"address": "street5",
"city": "test",
"country": "US"
}
},
{
"location": {
"address": "street5",
"city": "test",
"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"
}
}
}
}
])
即使您的轨道阵列有多个对象,这也会将它们相加。操场
推荐阅读
- java - Maven 项目继承:无法解析来自父项目的导入
- python - 如何根据多个属性对列表项进行排序,而最后一个优先级是字母?
- javascript - 是否可以用线条或不是矩形的画布制作带有背景的画布?
- python-3.x - 为什么在 python 中使用求和方程只显示 0 个值
- c# - DateTime.ToString(String, IFormatProvider) 不适用于 Xamarin.Forms 中的波斯文 CultureInfo“fa-IR”
- java - Java中使用DAO模式的多对多关系
- r - 如果输入通过,updateTabItems 在模块中不起作用
- c# - 在 chrome C# 中更改下载的文件名
- c# - 使用 Grid 在多列上显示项目
- animation - 有没有办法阻止耀斑动画循环播放?