ObjectId comparison

1,370 views
Skip to first unread message

octave

unread,
Mar 2, 2011, 8:17:47 AM3/2/11
to mongodb-user
Hi,
I have a problem in ObjectIds comparison.

Here is a simple test:
> a = ObjectId()
ObjectId("4d6e43c970953cc4bf43b8cc")
> db.test.insert({a:a})
> doc = db.test.findOne()
{
"_id" : ObjectId("4d6e43d170953cc4bf43b8cd"),
"a" : ObjectId("4d6e43c970953cc4bf43b8cc")
}
> doc.a === a
false
> doc.a.toString() === a.toString()
true
> db.version()
1.7.4

Are there any ways to compare "a" ObjectIds without casting it to
string?


Thanks.

Scott Hernandez

unread,
Mar 2, 2011, 9:56:47 AM3/2/11
to mongod...@googlegroups.com
a.equals(doc.a)

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

octave

unread,
Mar 2, 2011, 10:40:51 AM3/2/11
to mongodb-user
Thanks, Scott.

But originally, I've met this problem in Array.indexOf function:

> a = ObjectId()
ObjectId("4d6e6500d47a874a1035352c")
> arr = [a]
[ ObjectId("4d6e6500d47a874a1035352c") ]
> arr.indexOf(a)
0
> arr.indexOf(ObjectId("4d6e6500d47a874a1035352c"))
-1

What can I do in this case (except cycles)?
For example, if the size of array is about 1k elements, native
Array.indexOf is much more efficient than compare it one by one inside
of for() cycle.

Scott Hernandez

unread,
Mar 2, 2011, 10:44:14 AM3/2/11
to mongod...@googlegroups.com
Yeah, that sounds like a bug then. I assume the indexOf is using ===
not .equals() for comparison.

For now I'd suggest you use your own function.

octave

unread,
Mar 2, 2011, 11:05:08 AM3/2/11
to mongodb-user
There's no profit to use own (pure) function for that (very slow in
comparison with indexOf).
It's ok if I will open an issue in mongodb jira on it?

Scott Hernandez

unread,
Mar 2, 2011, 11:07:54 AM3/2/11
to mongod...@googlegroups.com
On Wed, Mar 2, 2011 at 8:05 AM, octave <chi...@gmail.com> wrote:
> There's no profit to use own (pure) function for that (very slow in
> comparison with indexOf).
> It's ok if I will open an issue in mongodb jira on it?

Yes, please do.

octave

unread,
Mar 2, 2011, 11:26:04 AM3/2/11
to mongodb-user
http://jira.mongodb.org/browse/SERVER-2667

On Mar 2, 6:07 pm, Scott Hernandez <scotthernan...@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages