MongoDB学习之(三)增删查改

发现一篇Java操作MongoDb不错的文章,记录一下:

https://www.cnblogs.com/sa-dan/p/6836055.html

基本功能。

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

import org.bson.Document;

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


/**
 * @author  szy 
 * @version 创建时间:2018-3-31 下午9:48:59
 * 
 */
public class MongodbTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		//查询表
		MongoDatabase mgdb = mongoClient.getDatabase("test");
		
		System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase inof is : "+mgdb.getName());
        
        //表里表里的集合
        for (String name : mgdb.listCollectionNames()) {
            System.out.println("test表里的集合有:"+name);
        }
        
        //###########################
        //获得一个集合对象 
       MongoCollection<Document> coll = mgdb.getCollection("myTestCollection");

       //如果在集合中插入相同的_id,会报错  index: _id_ dup key: {
        Document document = new Document("_id", 2002).append("title", "MongoDB Insert Demo")
                .append("description","database")
                .append("likes", 30)
                .append("by", "yiibai point")
                .append("url", "http://www.yiibai.com/mongodb/");

        //往集合对插入一体爱记录
        coll.insertOne(document);
        
        //再插入一条不指定id的,会自动分配一个_id
        Document document2 = new Document("title", "MongoDB Insert Demo")
                .append("description","database")
                .append("likes", 30)
                .append("by", "yiibai point")
                .append("url", "http://www.yiibai.com/mongodb/");
        coll.insertOne(document2);
        
        
        
        //多行插入
        List<Document> documents = new ArrayList<Document>();
        Document a1 = new Document("title", "2018");
        
        Document a2 = new Document("title", "2019");
              
        documents.add(a1);
        documents.add(a2);
        
        coll.insertMany(documents);
        System.out.println("Document inserted successfully");
      
        
        

	}

}

  

 

posted on 2018-04-09 22:54  手撕高达的村长  阅读(263)  评论(0编辑  收藏  举报

导航