在数组中查找一个值 [英] Find a value in array
问题描述
所以我的收藏是这样的:
So my collection is something like:
[
{"name": "one", "jobs": ["1","2","3","4","5"]},
{"name": "two", "jobs": ["6","7","8","9","10"]},
{"name": "three", "jobs": ["11","12","13","14","15"]},
]
我想创建一个查询,以根据jobs
中的值查找名称.因此,如果为jobs=2
,则名称应为one
;否则,名称为one
.如果为jobs=9
,则名称应为two
;如果为jobs=13
,则名称应为three
.我要放什么
db.collection.find({ ?? })
And I want to create a query to find the name based on the value from jobs
. So if jobs=2
, the name should be one
; if jobs=9
, the name should be two
; if jobs=13
, the name should be three
. What do i put in the
db.collection.find({ ?? })
谢谢.
推荐答案
只需补充另一个答案,如果您想从一系列工作中进行搜索,则可以执行以下操作:
Just complementing the other answer, if you wanna search from a range of jobs, you can do something like:
db.collection.find({jobs:{$in:["13","14"]}},{name:1})
如果要获取此数组的 slice ,则可以使用slice运算符.它有两个参数:第一个是初始索引,第二个是此索引之后的元素数.这是一个示例:
If you want to get a slice of this array, you can use the slice operator. It takes two parameters: The first is the initial index and the second is the number of elements after this index. Here's an example:
db.tasks.find({jobs:{$in:["13","14"]}},{name:1,jobs:{$slice : [0,2]}})
这将从数组的索引[0]中获取两个元素.
This will take two elements from the index [0] of the array.
这篇关于在数组中查找一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!