MongoDB聚合运算符:$indexOfArray

文章目录

$indexOfArray聚合运算符返回指定值在数组中第一次出现的索引位置,数组的索引从0开始。

语法

js 复制代码
{ $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] }

$indexOfArray参数说明:

  • <array>,字符串,可以是任何能够解析为数组的表达式,如果表达式解析为null或引用的字段不存在,$indexOfArray返回null。如果表达式不能解析为数组或null且引用的字段都存在,$indexOfArray将返回错误。
  • <search value>,字符串,可以是任意合法的表达式。
  • <start>,可选,整数或可以转换为整数的数值(如:2.0),必须大于等于0,用于指定从数组的哪个元素开始检索。
  • <end>,可选,整数或可以转换为整数的数值(如:2.0),必须大于等于0,用于指定结束检索的元素位置。如果指定了<end>就应该同时指定<start>,不然$indexOfArray会将<end>当作<start>。如果不指定,则为字符串的最后位置。

使用

  • 如果<search expression<array expression>中能检索到多次,$indexOfArray返回第一个检索到的位置索引。
  • 如果<array expression>null或引用的字段不存在,indexOfArray返回null
  • 如果<array expression>不是数组且不为空,或者<start><end>是负值,$indexOfArray返回错误。
  • 如果<search expression>在数组中未检索到或<start>大于<end><start>大于数组长度,则$indexOfArray返回-1

用下面的例子进一步说明:

例如 结果
{ $indexOfArray: [ [ "a", "abc" ], "a" ] } 0
{ $indexOfArray: [ [ "a", "abc", "de", ["de"] ], ["de"] ] } 3
{ $indexOfArray: [ [ 1, 2 ], 5 ] } -1
{ $indexOfArray: [ [ 1, 2, 3 ], [1, 2] ] } -1
{ $indexOfArray: [ [ 10, 9, 9, 8, 9 ], 9, 3 ] } 4
{ $indexOfArray: [ [ "a", "abc", "b" ], "b", 0, 1 ] } -1
{ $indexOfArray: [ [ "a", "abc", "b" ], "b", 1, 0 ] } -1
{ $indexOfArray: [ [ "a", "abc", "b" ], "b", 20 ] } -1
{ $indexOfArray: [ [ null, null, null ], null ] } 0
{ $indexOfArray: [ null, "foo" ] } null
{ $indexOfArray: [ "foo", "foo" ] } Error

举例

使用下面的脚本创建inventory集合:

js 复制代码
db.inventory.insertMany( [
   { _id: 0, items: [ "one", "two", "three" ] },
   { _id: 1, items: [ 1, 2, 3 ] },
   { _id: 2, items: [ 1, 2, 3, 2 ] },
   { _id: 3, items: [ null, null, 2 ] },
   { _id: 4, items: [ 2, null, null, 2 ] },
   { _id: 5, items: null },
   { _id: 6, amount: 3 }
] )

下面的示例使用$indexOfArray查找2items数组中位置:

js 复制代码
db.inventory.aggregate( [ {
   $project: {
      index: { $indexOfArray: [ "$items", 2 ] }
   }
} ] )

返回结果如下:

js 复制代码
[
   { _id: 0, index: -1 },
   { _id: 1, index: 1 },
   { _id: 2, index: 1 },
   { _id: 3, index: 2 },
   { _id: 4, index: 0 },
   { _id: 5, index: null },
   { _id: 6, index: null }
]
相关推荐
数据库小组6 小时前
2026 年,MySQL 到 SelectDB 同步为何更关注实时、可观测与可校验?
数据库·mysql·数据库管理工具·数据同步·ninedata·selectdb·迁移工具
华科易迅6 小时前
MybatisPlus增删改查操作
android·java·数据库
Kethy__6 小时前
计算机中级-数据库系统工程师-计算机体系结构与存储系统
大数据·数据库·数据库系统工程师·计算机中级
SHoM SSER6 小时前
MySQL 数据库连接池爆满问题排查与解决
android·数据库·mysql
熬夜的咕噜猫7 小时前
MySQL备份与恢复
数据库·oracle
jnrjian7 小时前
recover database using backup controlfile until cancel 假recover,真一致
数据库·oracle
lifewange8 小时前
java连接Mysql数据库
java·数据库·mysql
大妮哟8 小时前
postgresql数据库日志量异常原因排查
数据库·postgresql·oracle
还是做不到嘛\.9 小时前
Dvwa靶场-SQL Injection (Blind)-基于sqlmap
数据库·sql·web安全
不写八个9 小时前
PHP教程004:php链接mysql数据库
数据库·mysql·php