在 MongoDB 中,我们在使用 find 查询记录的数组字段时,如果我们想只返回数组的某一项到另一项之间的所有项,我们可以用 $slice
修饰符加上数组。
db_name.collection_name.find({query}, {filed:{$slice:[startIndex, endIndex]}});
参数 | 描述 |
---|---|
db_name | 数据库名 |
collection_name | 集合名 |
query | 查询条件 |
filed | 要查询的字段 |
startIndex | 查询的数组的开始索引 |
endIndex | 查询的数组的结束索引 |
startIndex 表示数组的开始索引,endIndex 表示数组的结束索引,其中,startIndex 从 0 开始,endIndex 是开区间。
我们首先,使用 mongo 命令,连接上数据库,具体命令如下:
mongo
如下图所示:
现在,我们使用 use 命令,切换到 haicoder 数据库,具体命令如下:
use haicoder
现在,我们使用 insertMany 插入三条记录,具体命令如下:
db.haicoder.insertMany([{"url":"haicoder.net", "course":["Python", "Mysql", "MongoDB"]}, {"url":"haicoder", "course":["Java", "Cpp", "Python"]}, {"url":"m.haicoder.net", "course":["Golang", "MongoDB", "Mysql"]}])
执行完毕后,此时,如下图所示:
+
我们看到,此时提示我们成功插入了三条记录,现在,我们使用 find 对数组进行查询,并且只显示数组的第一项到第二项,具体命令如下:
db.haicoder.find({}, {_id:0, "course":{$slice:[0, 2]}})
执行完毕后,此时,如下图所示:
我们看到,此时查到的所有记录只显示了第一项和第二项,同时,我们再次查询,具体命令如下:
db.haicoder.find({}, {_id:0, "course":{$slice:[0, 1]}})
执行完毕后,此时,如下图所示:
我们看到,同样实现了对数组进行了查询,并且只显示了第一项。
在 MongoDB 中,我们在使用 find 查询记录的数组字段时,如果我们想只返回数组的某一项到另一项之间的所有项,我们可以用 $slice
修饰符加上数组。