在MongoDB中获取数组的第n个元素 [英] Get n-th element of an array in MongoDB

查看:28
本文介绍了在MongoDB中获取数组的第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我在 MongoDB 中的文档的一部分,我存储了一个对象数组.例如,如何仅查询数组的第 4 个元素?所以我不想取出整个数组,只取出第 4 个元素.

As part of my document in MongoDB I'm storing an array of objects. How can I query it for only the 4th element of the array for example? So I don't want the get the entire array out, just the 4th element.

推荐答案

使用 $slice.

db.foo.find({ bar : "xyz" } , { my_array : { $slice : [n , 1] } } )

将检索 foo 集合中所有文档的数组my_array"的第 n 个元素,其中 bar =xyz".

will retrieve the nth element of the array "my_array" of all documents in the foo collection where bar = "xyz".

MongoDB 文档中的一些其他示例:

Some other examples from the MongoDB documentation:

db.posts.find({}, {comments:{$slice: 5}}) // first 5 comments
db.posts.find({}, {comments:{$slice: -5}}) // last 5 comments
db.posts.find({}, {comments:{$slice: [20, 10]}}) // skip 20, limit 10
db.posts.find({}, {comments:{$slice: [-20, 10]}}) // 20 from end, limit 10

您可以在这里阅读:http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields

这篇关于在MongoDB中获取数组的第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆