gpt4 book ai didi

java - 删除 MongoDB 集合中 10% 的旧对象

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:16 25 4
gpt4 key购买 nike

例如,我想删除 10% 的对象。

我获取集合并按时间排序。现在我有一个迭代器。我想说删除,但是没用。清除不行啊如何只删除第一个对象?

尝试1

MongoCursor<Document> cursor = collection.find().sort(new BasicDBObject("utc-stamp", 1)).iterator();
while (cursor.hasNext()) {
Document document = (Document) cursor.next();
document.clear();

}

尝试2

MongoCursor<Document> iterator = collection.find().sort(new BasicDBObject("utc-stamp", 1)).iterator();
for(int i = 0; i< collection.count()-2; i++) {
iterator.next().clear();
}
while (iterator.hasNext()) {
docs.add(iterator.next());
}

我没有任何想法。我可以获得集合的名称和对象的大小。

希望你能帮助我。

最佳答案

collection.deleteOne(document);

您必须对集合调用删除操作才能从集合中删除文档。请参阅official documentation .

注意:如果要删除 100 个文档,则将进行 100 个单独的 DB 删除调用。另外,请考虑 @Siddharth Ajmera 使用上限集合的建议。

关于java - 删除 MongoDB 集合中 10% 的旧对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36498457/

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