mongodb删除文档

import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class MyMongodbDelTest {
    public static void main(String[] args) throws Exception{
        try{
            // 连接到 mongodb 服务
//            MongoClient mongoClient = new MongoClient("localhost", 27017);
            MongoClient mongoClient = MongoClients.create();

            // 连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
            System.out.println("Connect to database successfully");

//            com.mongodb.MongoCommandException: Command failed with error 48 (NamespaceExists): 'Collection already exists. NS: mycol.test' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Collection already exists. NS: mycol.test", "code": 48, "codeName": "NamespaceExists"}
//            mongoDatabase.createCollection("test");
//            System.out.println("集合创建成功");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            System.out.println("集合 test 选择成功");


            //删除符合条件的第一个文档
            collection.deleteOne(Filters.eq("likes", 200));
            //删除所有符合条件的文档
            collection.deleteMany (Filters.eq("likes", 200));
            //检索查看结果
            FindIterable<Document> findIterableDel = collection.find();
            MongoCursor<Document> mongoCursorDel = findIterableDel.iterator();
            while(mongoCursorDel.hasNext()){
                System.out.println(mongoCursorDel.next());
            }

        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }

    }

}

 

posted on 2022-06-02 11:54  oktokeep  阅读(90)  评论(0编辑  收藏  举报