[英]How to add several documents using capped collection via mongodb Java driver 3.4+?
I want to add several document using capped collection and writing like: 我想使用封顶集合并像这样写一些文档:
// this code insert only first document using capped collection
MongoDatabase database = mongoClient.getDatabase("db");
database.createCollection("capped_collection",
new CreateCollectionOptions().capped(true).sizeInBytes(536870912).maxDocuments(5000));
MongoCollection<Document> collection = database.getCollection("capped_collection");
Document found = database.getCollection("capped_collection").find(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price)).first();
if (found == null) {
collection.insertOne(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price));
mongoClient.close();
}
In this case capped collection gives me to insert only first document and that's all (I want several not one). 在这种情况下,有上限的集合使我只能插入第一个文档,仅此而已(我要几个而不是一个)。 If I create normal collection I can insert several docs.
如果我创建普通收藏,我可以插入几个文档。 Why it happens?
为什么会发生?
MongoDatabase database = mongoClient.getDatabase("db");
MongoCollection<Document> collection = database.getCollection("normal_collection");
Document found = database.getCollection("normal_collection").find(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price)).first();
if (found == null) {
collection.insertOne(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price));
mongoClient.close();
}
In this way I can insert several documents using normal collection. 这样,我可以使用普通集合插入多个文档。
As I understand properly, there is no difference in the code between inserting documents into a capped collection and a normal collection, but in fact I have different results. 据我正确理解,将文档插入有上限的集合和普通集合之间的代码没有什么区别,但是实际上我得到的结果是不同的。
Updated: Just tried manually to add docs in capped collection via powershell 更新: 刚刚尝试通过Powershell在封闭的集合中添加文档
In powershell manually could be like: 在powershell中,手动可能像这样:
Documents looks like (as test): 文档看起来像(作为测试):
Correct me, please, if I'm wrong. 请纠正我,如果我错了。 Thanks for help.
感谢帮助。
Finally solve it. 终于解决了。 I needed to check for an existing collection :
我需要检查现有集合 :
boolean collectionExists = mongoClient.getDatabase("db_feed").listCollectionNames()
.into(new ArrayList<>()).contains("capped_collection");
if(!collectionExists) {
database.createCollection("capped_collection",
new CreateCollectionOptions().capped(true).sizeInBytes(327).maxDocuments(1).autoIndex(true));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.