user1848018
user1848018

Reputation: 1106

Using objectId as an array in mongodb

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.

Upvotes: 0

Views: 1206

Answers (2)

WiredPrairie
WiredPrairie

Reputation: 59763

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.

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311865

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; } 
}

Upvotes: 1

Related Questions