开发-数据库-MongoDB初探

MangoDB(3.03)基本操作,增删改查。

package test;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Locale;

import org.bson.Document;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.result.UpdateResult;

/*
 * you can find anything you need at 
 * 1) https://docs.mongodb.org/getting-started/java/aggregation/
 * 2) http://api.mongodb.org/java/3.0/overview-summary.html
 */

public class Demo_MangoDB {

	public static void main(String[] args) {
		try {
			MongoClient mongoClient = new MongoClient("localhost", 27017);
			MongoDatabase db = mongoClient.getDatabase("test");
			
			
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
			
			// If you attempt to add documents to a collection that does not exist, MongoDB will create the collection for you.
			db.getCollection("restaurants").insertOne(
			        new Document("address",
			                new Document()
			                        .append("street", "2 Avenue")
			                        .append("zipcode", "10075")
			                        .append("building", "1480")
			                        .append("coord", Arrays.asList(-73.9557413, 40.7720266)))
			                .append("borough", "Manhattan")
			                .append("cuisine", "Italian")
			                .append("grades", Arrays.asList(
			                        new Document()
			                                .append("date", format.parse("2014-10-01T00:00:00Z"))
			                                .append("grade", "A")
			                                .append("score", 11),
			                        new Document()
			                                .append("date", format.parse("2014-01-16T00:00:00Z"))
			                                .append("grade", "B")
			                                .append("score", 17)))
			                .append("name", "Vella")
			                .append("restaurant_id", "41704620"));
			
			FindIterable<Document> iterable = db.getCollection("restaurants").find();
			
			iterable.forEach(new Block<Document>() {

				@Override
				public void apply(Document document) {
					System.out.println(document);
				}
				
			});
			
			//Find or Query Data
			iterable = db.getCollection("restaurants").find(new Document("borough", "Manhattan"));
			//iterable = db.getCollection("restaurants").find(Filters.eq("borough", "Manhattan"));
			iterable = db.getCollection("restaurants").find(new Document("address.zipcode", "10075"));
			iterable = db.getCollection("restaurants").find(Filters.eq("address.zipcode", "10075"));
			iterable = db.getCollection("restaurants").find(Filters.eq("grades.grade", "B"));
			iterable = db.getCollection("restaurants").find(new Document("grades.score", new Document("$gt", 30)));
			iterable = db.getCollection("restaurants").find(Filters.gt("grades.score", 30));
			iterable = db.getCollection("restaurants").find(new Document("cuisine", "Italian").append("address.zipcode", "10075"));
			iterable = db.getCollection("restaurants").find(Filters.and(Filters.eq("cuisine", "Italian"), Filters.eq("address.zipcode", "10075")));
			iterable = db.getCollection("restaurants").find(
			        new Document("$or", Arrays.asList(new Document("cuisine", "Italian"),
			                new Document("address.zipcode", "10075"))));
			iterable = db.getCollection("restaurants").find(Filters.or(Filters.eq("cuisine", "Italian"), Filters.eq("address.zipcode", "10075")));
			iterable = db.getCollection("restaurants").find().sort(new Document("borough", 1).append("address.zipcode", 1)); //1 for ascending and -1 for descending.
			db.getCollection("restaurants").find().sort(Sorts.ascending("borough", "address.zipcode"));
			
			//Update Data
			UpdateResult ur = db.getCollection("restaurants").updateOne(new Document("name", "Juni"), new Document("$set", new Document("cuisine", "American (New)")).append("$currentDate", new Document("lastModified", true)));
			System.out.println(ur.getModifiedCount());
			db.getCollection("restaurants").updateOne(new Document("restaurant_id", "41156888"),
			        new Document("$set", new Document("address.street", "East 31st Street")));
			db.getCollection("restaurants").updateMany(new Document("address.zipcode", "10016").append("cuisine", "other"),
									new Document("$set", new Document("cuisine", "Category To Be Determined")).append("$currentDate", new Document("lastModified", true)));
			db.getCollection("restaurants").replaceOne(new Document("restaurant_id", "41704620"),
			        new Document("address",
			                new Document()
			                        .append("street", "2 Avenue")
			                        .append("zipcode", "10075")
			                        .append("building", "1480")
			                        .append("coord", Arrays.asList(-73.9557413, 40.7720266)))
			                .append("name", "Vella 2"));
			
			//Remove Data
			db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan")); //Remove All Documents That Match a Condition
			//db.getCollection("restaurants").deleteMany(new Document()); //Remove All Documents
			//db.getCollection("restaurants").drop(); //Drop a Collection
			
			//Data Aggregation
			AggregateIterable<Document> aggIterable = db.getCollection("restaurants").aggregate(Arrays.asList(
					new Document("$group", new Document("_id", "$building").append("count", new Document("$sum", 1)))));
			aggIterable = db.getCollection("restaurants").aggregate(Arrays.asList(
					new Document("$match", new Document("address.street", "2 Avenue").append("address.building", "1480")),
					new Document("$group", new Document("_id", "$address.zipcode").append("count", new Document("$sum", 1)))
					));
			
			
			aggIterable.forEach(new Block<Document>() {

				@Override
				public void apply(Document document) {
					// TODO Auto-generated method stub
					System.out.println(document.toJson());
				}
				
			});
			
			//db.drop(); //Drop the current Database
			//mongoClient.dropDatabase("test");
			mongoClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Flask-APScheduler在MongoDB中实现定时任务,只需要在Flask应用中定义一个定时任务,并将其配置为在MongoDB中运行。具体代码如下:from flask_apscheduler import APSchedulerscheduler = APScheduler()# Configure the scheduler to use MongoDB as its job store scheduler.add_jobstore('mongodb', host='localhost', database='your_database_name')@scheduler.task('interval', id='do_job_1', seconds=30) def job_1(): print("Job 1 executed")@scheduler.task('cron', id='do_job_2', day_of_week='mon-sun', hour='12', minute='30') def job_2(): print("Job 2 executed")# Start the scheduler scheduler.start() ### 回答2: 要使用Flask-APScheduler实现数据库MongoDB定时任务,首先需要安装Flask-APScheduler和pymongo库。在Flask应用程序中,可以使用以下代码实现: 1. 首先,在app.py文件中导入所需的模块和库: ```python from flask import Flask from flask_apscheduler import APScheduler from pymongo import MongoClient ``` 2. 创建Flask应用程序实例: ```python app = Flask(__name__) ``` 3. 配置MongoDB连接并创建MongoDB客户端: ```python app.config['MONGO_URI'] = 'mongodb://localhost:27017/db_name' mongo_client = MongoClient(app.config['MONGO_URI']) ``` 请注意,`db_name`应替换为你的实际数据库名称,`localhost:27017`应替换为你的MongoDB服务器地址和端口。 4. 初始化APScheduler实例并配置任务存储: ```python scheduler = APScheduler() scheduler.init_app(app) scheduler.start() ``` 5. 创建一个定时任务函数,该函数将执行需要定时执行的操作。这里以向MongoDB数据库中插入一条记录为例: ```python def insert_data(): db = mongo_client.db_name collection = db.collection_name data = {'name': 'John', 'age': 30} collection.insert_one(data) ``` 请注意,`db_name`和`collection_name`应替换为你的实际数据库和集合名称。 6. 创建一个定时任务,并将其添加到APScheduler中: ```python scheduler.add_job(func=insert_data, trigger='interval', seconds=60) ``` 这将每隔60秒执行一次`insert_data`函数。 7. 最后,在Flask应用程序的入口处,启动Flask应用程序: ```python if __name__ == '__main__': app.run() ``` 以上代码片段演示了如何使用Flask-APScheduler和pymongo库实现数据库MongoDB定时任务的基本步骤。根据实际需求,你可以根据需要调整设置和任务函数。 ### 回答3: 要使用Flask-APScheduler实现MongoDB数据库的定时任务,需要先安装Flask和Flask-APScheduler库,并且确保MongoDB数据库已经正确安装和配置。 首先,在Flask应用中导入所需要的库和模块: ```python from flask import Flask from flask_apscheduler import APScheduler from pymongo import MongoClient ``` 然后,创建Flask应用和APScheduler实例并配置MongoDB数据库的连接: ```python app = Flask(__name__) scheduler = APScheduler() scheduler.init_app(app) # 配置MongoDB数据库连接 client = MongoClient('mongodb://localhost:27017/') # 替换为实际的MongoDB连接地址 db = client['mydatabase'] # 替换为实际的数据库名称 ``` 接下来,创建一个定时任务函数,该函数在特定时间间隔内会被调度执行,并且可以在函数中访问MongoDB数据库: ```python @scheduler.task('interval', id='my_job', minutes=30) def my_task(): collection = db['mycollection'] # 替换为实际的集合名称 # 在此处添加需要执行的MongoDB操作,例如插入、更新、删除等 # 例如:collection.insert_one({"name": "example"}) ``` 最后,启动定时任务调度器和Flask应用: ```python @app.route('/') def index(): return 'Flask-APScheduler MongoDB Demo' if __name__ == '__main__': scheduler.start() app.run() ``` 启动应用后,定时任务会按照预定的时间间隔执行,并且可以在`my_task()`函数中进行MongoDB的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值