MongoDB-投影操作(1)-$slice

本文介绍了MongoDB中$slice操作符的功能及其使用方法。$slice用于控制查询返回的数组元素数量,可通过正数、负数及数组形式指定要返回的元素范围。文章通过多个实例展示了如何选取数组中的前几项、后几项以及跳过某些项后的特定数量元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$slice (projection)

The sliceoperatorcontrolsthenumberofitemsofanarraythataqueryreturns.Forinformationonlimitingthesizeofanarrayduringanupdatewithpush, see the $slice modifier instead.

Consider the following prototype query:

db.collection.find( { field: value }, { array: {$slice: count } } );

This operation selects the document collection identified by a field named field that holds value and returns the number of elements specified by the value of count from the array stored in the array field. If count has a value greater than the number of elements in array the query returns all elements of the array.

$slice accepts arguments in a number of formats, including negative values and arrays. Consider the following examples:

db.posts.find( {}, { comments: { $slice: 5 } } )

Here, $slice selects the first five items in an array in the comments field.

db.posts.find( {}, { comments: { $slice: -5 } } )

This operation returns the last five items in array.

The following examples specify an array as an argument to $slice. Arrays take the form of [ skip , limit ], where the first value indicates the number of items in the array to skip and the second value indicates the number of items to return.

db.posts.find( {}, { comments: { $slice: [ 20, 10 ] } } )

Here, the query will only return 10 items, after skipping the first 20 items of that array.

db.posts.find( {}, { comments: { $slice: [ -20, 10 ] } } )

This operation returns 10 items as well, beginning with the item that is 20th from the last item of the array.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值