MongoDB之java增删查改

package com.example.demo.testmongo;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;

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

public class MongoTest {

    public static void main(String[] args) {
        try {

            // 1)连接到 mongo 服务,无密码和用户名
            MongoClient mongoClient = new MongoClient("localhost", 27017);


            /*
            // 2) 需要用户名和密码连接集群服务
            MongoCredential credential = MongoCredential.createCredential("hurw", "hurw", "123456".toCharArray());
            MongoClient mongo = new MongoClient(
                    Arrays.asList(new ServerAddress("10.4.0.1", 27017),
                            new ServerAddress("10.4.0.2", 27017),
                            new ServerAddress("10.4.0.3", 27017),
                            new ServerAddress("10.4.0.4", 27017),
                            new ServerAddress("10.4.0.5", 27017)),
                    Arrays.asList(credential));
             */

            System.out.println("Connect to database successfully");
            // 获取数据库名
            MongoDatabase mongoDatabase = mongoClient.getDatabase("hurw");

            // 创建 collection
            mongoDatabase.createCollection("test");

            // (增)插入文档
            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            Document document = new Document();
            // 以下两种办法都可以加入元素
            document.append("name","hurw");
            document.put("age",18);

            List<Document> documentList = new ArrayList<>();
            documentList.add(document);
            collection.insertMany(documentList);

            // (查)遍历文档
            MongoCollection<Document> collection1 = mongoDatabase.getCollection("test");
            // 获取迭代器FindIterable<Document>
            FindIterable<Document> findIterable = collection1.find();
            // 获取游标MongoCursor<Document>
            MongoCursor<Document> mongoCursor = findIterable.iterator();
            while (mongoCursor.hasNext()){
                System.out.println(mongoCursor.next());
            }

            // 查询条件
            Document query = new Document("first_ip_addr", new Document("$lte", ipl)).append("last_ip_addr", new Document("$gte", ipl));
                    FindIterable<Document> findIterable1 = collection1.find(query);
                    MongoCursor<Document> mongoCursor1 = findIterable1.iterator();
                    while (mongoCursor1.hasNext()) {
                        Document document1 = mongoCursor1.next();
                        document1.get("XXX");
                    }




            // 遍历文档的另一种方式:
            String url = "mongodb://10.40.20.20:27017/admin";
            MongoClientURI mongoClientUri = new MongoClientURI(url);
            MongoClient mongoclient = new MongoClient(mongoClientUri);
            MongoCollection collection = mongoclient.getDatabase(dbName).getCollection (collectionName);

            Bson filter1 = Filters.eq("id",1);
            FindIterable<Document> findIterable = collection.find(filter1);
            MongoCursor<Document> mongoCursor = findIterable.iterator();
            while (mongoCursor.hasNext()){
                Document document = mongoCursor.next();
                int netId = Integer.valueOf(document.get("id").toString());
                ....
            }


            // (改)更新/修改元素
            collection.updateMany(Filters.eq("age",18),
                    new Document("$set",new Document("age",22)));
            // 修改后再遍历
            MongoCollection<Document> collection2 = mongoDatabase.getCollection("test");
            // 获取迭代器FindIterable<Document>
            FindIterable<Document> findIterable1 = collection2.find();
            // 获取游标MongoCursor<Document>
            MongoCursor<Document> mongoCursor1 = findIterable1.iterator();
            while (mongoCursor1.hasNext()){
                System.out.println(mongoCursor1.next());
            }

            // (删)删除元素
            collection1.deleteOne(Filters.eq("age",22));
            collection1.deleteMany(Filters.eq("name","hurw"));

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}

MongoDB  备份(mongodump)与恢复(mongorestore)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Python 中的 requests、BeautifulSoup 和 pymongo 库来爬取天气数据并导入到 MongoDB 数据库中进行增删查改操作。 下面是一个简单的示例代码,可以爬取某个城市的天气数据并将其存储到 MongoDB 中: ```python import requests from bs4 import BeautifulSoup from pymongo import MongoClient # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 设置要爬取的城市名称和链接 city_name = '上海' url = f'http://www.weather.com.cn/weather/{101020100}.shtml' # 发送请求并获取响应 res = requests.get(url, headers=headers) soup = BeautifulSoup(res.text, 'html.parser') # 获取天气数据 weather_data = { 'city': city_name, 'date': soup.find('input', id='fc_24h_internal_update_time').get('value'), 'temperature': soup.find('p', class_='tem').span.text, 'weather': soup.find('p', class_='wea').text, 'wind': soup.find('p', class_='win').span.text } # 连接 MongoDB 数据库 client = MongoClient('mongodb://localhost:27017/') db = client['weather'] col = db['weather_data'] # 插入数据 col.insert_one(weather_data) # 查询数据 result = col.find_one({'city': city_name}) print(result) # 更新数据 col.update_one({'city': city_name}, {'$set': {'temperature': '20℃'}}) # 删除数据 col.delete_one({'city': city_name}) ``` 需要注意的是,如果要在 MongoDB 中进行增删查改操作,需要先连接到 MongoDB 数据库,并获取到要操作的集合(collection)。在本示例中,我们连接到名为 "weather" 的数据库,并获取到名为 "weather_data" 的集合。同时,需要根据具体需求来编写插入、查询、更新和删除数据的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值