arrays - mongodb 在聚合中使用 $count
问题描述
我有一组汽车,其中一个字段是一个数组,让我们说一下:
"designers": [
"John Smith",
"Jane Smith",
]
我有很多设计师,让我们说一下:
"topDesigners": [
"Brad Johnson",
"Kevin Williams",
"John Smith"
]
我想数一数设计师中有多少是第一位的。
例如:
"designers": [
"Kevin Williams",
"Jane Smith",
]
期望结果:count = 1
"designers": [
"Jane Smith",
"John Smith"
]
期望结果:count = 1
"designers": [
"Kevin Huntzberger",
"Brad Johnson",
"John Smith"
]
期望结果:count = 2
解决方案
setIntersection是实现这一点的方法。
拿着这份文件:
{
designers: [
"John Smith",
"Jane Smith"
],
topDesigners: [
"Brad Johnson",
"Kevin Williams",
"John Smith"
]
}
您可以应用以下聚合查询来检索设计器和 topDesigners 数组中的元素。和 $size 来获取这个新数组的大小:
db.collection.aggregate([
{
$project: {
designers: "$designers",
topDesigners: "$topDesigners",
areInBoth: {
$setIntersection: [
"$designers",
"$topDesigners"
]
},
areInBothSize: {
$size: {
$setIntersection: [
"$designers",
"$topDesigners"
]
}
}
}
}
])
将导致:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"areInBoth": [
"John Smith"
],
"areInBothSize": 1,
"designers": [
"John Smith",
"Jane Smith"
],
"topDesigners": [
"Brad Johnson",
"Kevin Williams",
"John Smith"
]
}
]
推荐阅读
- bash - 从 PROMPT_COMMAND 访问最新命令(不是 args)
- c - 是否有可以将从 char 数组输入的数字转换为 int 数组的函数?
- perl - 如何在perl中以原始字节十六进制形式打印字符串?
- zsh - zsh 暂时禁用函数中的别名
- excel - Workbooks.Open() 上的 Excel 加载项问题卡在 Excel 主屏幕上
- perl - Perlbrew 没有列出已安装的 Perl 版本
- vuetify.js - 如何更改 Vuetify 中数据表的背景颜色?
- python - 无服务器 python 无法导入模块处理程序,并且可能无法使用 sls deploy 正确 dockerizing
- python - 将输入字符串张量转换为 python 字符串
- wordpress - Wordpress URL 重写问题