0

In javascript we can find the location of a specific string within an array using indexOf of

> ["aa","bb"].indexOf("bb")
1 

I want to do the same with objectIds in mongodb for example

> ids= db.foo1.distinct('_id');
[
        ObjectId("50d38d775f2b6c6e3393d6b0"),
        ObjectId("50d38d835f2b6c6e3393d6b1")
]
> id0=db.foo1.findOne()._id
ObjectId("50d38d775f2b6c6e3393d6b0")

I am looking for a way to do something like ids.indexOf(id0) that will give me the location of id0 within ids. I can convert everything to strings and then use the indexOf but I was hoping to find a simpler way to do this.

2 Answers 2

1

I don't think there's a one-liner for this and you'd need to use a for loop:

for (var i=0; i<ids.length; i++) { 
    if (ids[i].equals(id0)) { ixOfId0 = i; break; } 
}
Sign up to request clarification or add additional context in comments.

1 Comment

I did a similar thing. I wish there was a smarter way to do this. Thanks a lot anyways
1

If the list doesn't change frequently (or is only added to), consider just adding the documents with an index: { i: 0, r: ObjectId('....') }, where the i field represents the index.

Then db.foo1.find( { 'list.r' : ObjectId('...') }). The result would have the index by looking at the field i in the resulting document.

But, if the list is long, this is always going to be an O(N) operation as it has to search through every array element to find the match. You may need to create an index to improve performance.

2 Comments

The data set is way too big and I can't change it but thanks for the comment
How are you using the "index" value? Seems like the data may not be structured efficiently for MongoDB? Also, there's no guarantee of order unless you've explicitly put them in an array. Using Distinct isn't going to guarantee a particular order (and using distinct with _id doesn't make sense as _id must be unique/distinct per mongodb).

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.