当前位置:Gxlcms > 数据库问题 > MongoDB(3)--Java 操作 MongoDB 的 API

MongoDB(3)--Java 操作 MongoDB 的 API

时间:2021-07-01 10:21:17 帮助过:13人阅读

类比JDBC写法,相对比较偏底层

package com.lf;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class MongoCRUDTest {
	
	public static void main(String[] args) {
		
		Mongo mongo = new Mongo("192.168.25.128",27017);
		
		DB db = new DB(mongo,"lf-demo");
		
		DBCollection collection = db.getCollection("member");
		//类比JDBC
		DBObject dbObject = new BasicDBObject();
		dbObject.put("name", "lf");
		dbObject.put("age", "18");
		dbObject.put("addr", "anhui hefei");
		
		WriteResult insert = collection.insert(dbObject);
		System.out.println(insert+"---------");
		
		DBCursor dbCursor = collection.find();
		for(Object obj : dbCursor){
			System.out.println(obj);
		}
	}
}

 官方快速入门demo

package com.lf;

import java.util.Arrays;

import org.bson.Document;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoTest {
	public static void main(String[] args) {

		MongoClient mongoClient = MongoClients.create("mongodb://192.168.25.128:27017");
		MongoDatabase mongoDatabase = mongoClient.getDatabase("lf-demo");
		MongoCollection<Document> collection = mongoDatabase.getCollection("lf-member");
		Document document = new Document("name", "lf").append("age", "18")
				.append("address", Arrays.asList("anhui", "hefei"))
				.append("position", new Document("x", "125").append("y", "172"));
		collection.insertOne(document);

	}
}

mongoDB框架:封装了mongoDB基本的操作

Morphia  mongoDb的第一个orm框架

 

mongoTemplate  spring封装的

 

MongoDB(3)--Java 操作 MongoDB 的 API

标签:nbsp   ddr   god   get   out   第一个   封装   ODB   oda   

人气教程排行