Mongodb批量操作中的跟踪操作 [英] Tracing operations in Mongodb Bulk Operation

查看:114
本文介绍了Mongodb批量操作中的跟踪操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MongoDB 2.6.1。我的问题是 -
是否有可能在批量操作中跟踪_id?
假设我为BulkWriteOperation创建了一个对象,例如要从'A'集合插入'B'集合的50个文档。我还需要 保留成功写入操作列表和写入操作失败

I am using MongoDB 2.6.1. The question from me is that- "Is it possible for keep a track of _id in Bulk Operations??" Suppose if I have created one object for BulkWriteOperation, for example 50 documents to be inserted to the 'B' collection from 'A' collection. I need keep a list of successful write operations and failed write operations also.

批量插入和删除工作正常精细。但问题是 -
- 我需要跟踪_ids,查询 - 查找A 插入B集合的文档同时,我需要保留一个_id列表(成功和失败的操作)。我需要删除A集合中的文档,仅用于那些成功的操作并保留失败的文档 -

Bulk Inserts and deletes are working fine. But the question is that- -- "I need to keep a track of _ids, for a query- find the documents from A and insert to B collection. In the mean while, I need to keep a list of _ids (successful and failed operations). I need to delete the documents in A collection, only for those successful operations and keep failed documents as it is"--

请帮帮我。

感谢你:) :)

推荐答案

首先,您需要使用 UnorderedBulkOperation 来执行整个批处理。您将需要在 BulkWriteOperation.execute()周围使用try / catch,捕获 BulkWriteException ,可以访问 BulkWriteError 以及 BulkWriteResult

First, you'll need to use UnorderedBulkOperation for the entire batch to execute. You will need to use a try/catch around your BulkWriteOperation.execute(), catching BulkWriteException which will give you access to a list of BulkWriteError as well as the BulkWriteResult.

这是一个快速而肮脏的例子:

Here's a quick and dirty example:

MongoClient m = new MongoClient("localhost");
DB db = m.getDB( "test" );
DBCollection coll = db.getCollection( "bulk" );
coll.drop();
coll.createIndex(new BasicDBObject("i", 1), new BasicDBObject("unique", true));

BulkWriteOperation bulkWrite = coll.initializeUnorderedBulkOperation();

for (int i = 0; i < 100; i++) {
    bulkWrite.insert(new BasicDBObject("i", i));
}
// Now add 10 documents to the batch that will generate a unique index error
for (int i = 0; i < 10; i++) {
    bulkWrite.insert(new BasicDBObject("i", i));
}

BulkWriteResult result = null;
List<BulkWriteError> errors = null;
try {
    result = bulkWrite.execute();
} catch (BulkWriteException bwe) {
    bwe.printStackTrace();
    errors = bwe.getWriteErrors();
    result = bwe.getWriteResult();
}

for (BulkWriteError e : errors) {
    System.out.println(e.getIndex() + " failed");
}

System.out.println(result);

这篇关于Mongodb批量操作中的跟踪操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆