No 'duplicate key' exception on insert in C++

260 views
Skip to first unread message

Melvin

unread,
Jul 7, 2010, 10:16:33 AM7/7/10
to mongodb-user
There is an unique index on two fields to prevent duplicates:

BSONObjBuilder index;
index.append( "name", 1 );
index.append( "value", 1 );
mDBConn.ensureIndex( "my.objects", index.obj( ), true );

However, the code in the following snippet, doesn't throw an exception
when I try to insert a duplicate:

try
{
// Insert into DB
BSONObjBuilder builder;
data->serialize( builder );
mDBConn.insert( "my.objects", builder.obj() );
}
catch ( DBException &e )
{
cout << "Error inserting: " << e.getCode() << " " << e.what();
}

The duplicate isn't saved into the database, so that's expected
behavior. What I also would expect, is an exception being thrown in C+
+, but that doesn't happen.

In the output of mongod I notice the error/exception is detected:

Caught Assertion in insert , continuing
insert my.objects exception userassert:E11000 duplicate key error
index: my.objects.$name_1_value_1 dup key { : "Foo", : "Bar" }

Is the issue, described above, a bug perhaps? Or am I doing something
wrong?

Eliot Horowitz

unread,
Jul 7, 2010, 10:18:34 AM7/7/10
to mongod...@googlegroups.com
You need to call getLastError or use safe mode - though I'm not sure
safe mode for c++ really exists yet.

> --
> 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.
>
>

Melvin

unread,
Jul 8, 2010, 11:08:18 AM7/8/10
to mongodb-user
On 7 jul, 16:18, Eliot Horowitz <eliothorow...@gmail.com> wrote:
> You need to call getLastError or use safe mode - though I'm not sure
> safe mode for c++ really exists yet.

Safe mode doesn't exist (yet).

I am unsure if the getLastError method is what I am looking for, but I
will experiment a bit with the method.

However, I still think the exception should be thrown. Perhaps I
should file a feature request then.

Michael Dirolf

unread,
Jul 8, 2010, 11:15:15 AM7/8/10
to mongod...@googlegroups.com
Yeah, a feature request for safe mode support is a good idea. Safe
mode basically just calls getLastError automatically, so you can do it
manually for now as a workaround.

Reply all
Reply to author
Forward
0 new messages