我在MongoDB中有一个唯一的索引,以避免重复。
我正在尝试将简单的代码从java转换为c ++ 这是我将代码插入MongoDB的代码。 代码工作正常但当我尝试插入相同的文档时,应用程序停止工作。
mongocxx::client conn{ mongocxx::uri{ "mongodb://localhost:27017" } };
mongocxx::write_concern writeConcern;
writeConcern.acknowledge_level(mongocxx::write_concern::level(1));
QFile inputFile(path);
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
bsoncxx::builder::stream::document document{};
auto collection = conn["TestDB"]["fdevices"];
QString line = in.readLine();
std::string utf8_text = line.toUtf8().constData();
document << "Data" << utf8_text;
collection.insert_one(document.view());
}
inputFile.close();
}
这是我在java中使用的代码。 在java中,我可以通过使用mongoClient.setWriteConcern(new WriteConcern(0,10))来简单地忽略重复项;并继续循环到下一个文档。
MongoClient mongoClient = new MongoClient(asList( new ServerAddress(host+":"+port)),
singletonList(MongoCredential.createScramSha1Credential(uname.getText(),
MongoClientOptions.builder().serverSelectionTimeout(2000)
.build());
mongoClient.setWriteConcern(new WriteConcern(0, 10));
DB db = mongoClient.getDB(dblist.getSelectedValue().toString());
DBCollection bookCollection = db.getCollection(collectionss.getSelectedValue().toString());
for (int i = 0; i <sixe; i++) {
server.prolab.setText("Uploaded files: "+i+" Total files: "+sixe);
BasicDBObject doc = new BasicDBObject("Data",dataList.getModel().getElementAt(i));
bookCollection.insert(doc);
}
答案 0 :(得分:2)
您没有正确定义writeConcern方法,请尝试这些代码。
mongocxx::client conn{ mongocxx::uri{ "mongodb://localhost:27017" } };
bsoncxx::builder::stream::document document{};
mongocxx::write_concern writeConcern;
writeConcern.acknowledge_level(mongocxx::write_concern::level::k_unacknowledged);
std::chrono::milliseconds timeout = std::chrono::milliseconds(5000);
auto collection = conn["TestDB"]["fdevices"];
collection.write_concern(writeConcern);
conn.write_concern(writeConcern);
QFile inputFile(path);
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
QString line = in.readLine();
std::string utf8_text = line.toUtf8().constData();
document << "Data" << utf8_text;
collection.insert_one(document.view());
}
inputFile.close();
}