mongodb删除文档

2022/6/3 2:20:21

本文主要是介绍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() );
        }

    }

}

 



这篇关于mongodb删除文档的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程