Reputation: 3434
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"]},
]
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({ ?? })
Thanks.
Upvotes: 0
Views: 132
Reputation: 2769
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})
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]}})
This will take two elements from the index [0] of the array.
Upvotes: 1
Reputation: 75984
You can try something like this.
The below query will select all rows where the jobs
array has the element with value "3"
and project the name
field.
db.collection.find({jobs:"3"},{name:1})
More here https://docs.mongodb.com/manual/reference/operator/query/eq/#array-element-equals-a-value
Upvotes: 2