Brian
Brian

Reputation: 3558

MongoDB: Determine index of item in array

Is there a way to determine the index of a retrieved item in an array in MongoDB?


I have an array of object ids inside some document.

{
    ids: [id1, id2, id3, ...]
}

I search the array for id3, and if it's found, I also want the position of the object added to the result. In this case, it's so I can insert more objects immediately after it in the array.

If I can't do this, how would I go about creating an ordered list of objects for which I can retrieve and easily modify the position of elements in the ordered list (since an insert operation on the list will result in modifying the position of all elements after the insert)?


answer:

Obtaining the positional index is NOT supported in mongodb. I will open a new question then about redesigning my application to deal with this limitation. Thanks everyone!

Upvotes: 0

Views: 96

Answers (1)

betseyb
betseyb

Reputation: 1332

The way I see it, you have two choices:

  • Retrieve the whole array, mutate it however you wish in your language of choice, and update the array in the db with your new array.

  • Come up with a data structure that supports whatever it is you are ultimately trying to do.

Upvotes: 1

Related Questions