0

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This works. But what if i want to find 2 names. I tried {jobs:"2" || jobs:"9" }. thanks. Also if I want to return everything from that value, not just the name what do i do? MySQ equivalent to SELECT *
You are welcome. For first part try {$or: [{jobs:"2"}, {jobs:"9"}]}. For second part get rid of {name:1}.
1

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.

4 Comments

This doesn't work. The name is not returned. And what do i do if I want to return the job number too? thanks.
Are you sure you run the correct code? the {name:1} means to put the name. If you want to return the name and all the jobs you can just do the query without the second part like db.collection.find({jobs:{$in:["1","2"]}}) or add the jobs to the projection db.collection.find({...},{name:1,jobs:1})
Thanks. I was making a type. Thanks. I can get all the values now.
Another thing please, what if the key, name is an array with some values, say 20 values and updating regularly. And I want to list the latest 5 values from that array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.