gpt4 book ai didi

java - 如何避免重复使用 Mongodb C++

转载 作者:行者123 更新时间:2023-11-30 02:22:45 27 4
gpt4 key购买 nike

我在 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);
}

最佳答案

您没有正确定义 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();
}

关于java - 如何避免重复使用 Mongodb C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com