iameven
iameven

Reputation: 348

How do Mongodb Batch Insert to a collection which has unique key?

I Has a Collection which has a unique key,when I do batch insert to this collection,but it will cancel the insert process.just like this: Data in Collection:

{

   "app_key" : "key",
   "insert_date" : "1438963200",
   "uuid" : "123"
}

The unique key is : app_key+uuid And then I insert data like this :

{

   "app_key" : "key",
   "insert_date" : "1438963200",
   "uuid" : "1234"
}

{
   "_id" : ObjectId("55c80dbf1a4a5fa61c03b503"),
   "app_key" : "key",
   "insert_date" : "1438963200",
   "uuid" : "123"
}

{

   "app_key" : "key",
   "insert_date" : "1438963200",
   "uuid" : "234"
}

And result In collection is

{

   "app_key" : "key",
   "insert_date" : "1438963200",
   "uuid" : "123"
}

{
   "app_key" : "key",
   "insert_date" : "1438963200",
   "uuid" : "1234"
}

So it cancel at uuid:123 object,Does this mongo's question or bug... Thanks.

Upvotes: 0

Views: 102

Answers (1)

iameven
iameven

Reputation: 348

I think The param can help solve this problem,like this:

    WriteResult wr = dbc.insert(obj1,new WriteConcern(0, 0, false, false, true));
    if (null == wr.getError()) {
        System.out.println("Insert Success");
    }

as the function define:

/**
 * Creates a WriteConcern object.
 * <p>Specifies the number of servers to wait for on the write operation, and exception raising behavior </p>
 *  <p> w represents the number of servers:
 *      <ul>
 *          <li>{@code w=-1} None, no checking is done</li>
 *          <li>{@code w=0} None, network socket errors raised</li>
 *          <li>{@code w=1} Checks server for errors as well as network socket errors raised</li>
 *          <li>{@code w>1} Checks servers (w) for errors as well as network socket errors raised</li>
 *      </ul>
 *  </p>
 * @param w number of writes
 * @param wtimeout timeout for write operation
 * @param fsync whether or not to fsync
 * @param j whether writes should wait for a journaling group commit
 * @param continueOnInsertError if batch inserts should continue after the first error
 */
public WriteConcern( int w , int wtimeout , boolean fsync , boolean j, boolean continueOnInsertError) {
    _w = w;
    _wtimeout = wtimeout;
    _fsync = fsync;
    _j = j;
    _continueOnErrorForInsert = continueOnInsertError;
}

Upvotes: 1

Related Questions