java mongodb

来源:互联网 发布:php位运算 编辑:程序博客网 时间:2024/05/21 10:42

MongoDBdatabases组成,databasescollections组成,collectionsdocuments(相当于行)组成,而documentsfields(相当于列)组成。 MongoDB是异步写数据。 

 

1. 下载与安装。(这里就不写了)。

2. 连接数据库,这里需要在mongo的安装目录下cmd运行mongod --dbpath f:/mdb/data 指定数据库所在位置,目录需要手动创建。这个窗口不要关闭!重新运行cmd执行mongo则成功连接到数据库。

3. Help指令。

        db.help()                    help on db methods

        db.mycoll.help()             help on collection methods

        sh.help()                    sharding helpers

        rs.help()                    replica set helpers

        help admin                   administrative help

        help connect                 connecting to a db help

        help keys                    key shortcuts

        help misc                    misc things to know

        help mr                      mapreduce

 

        show dbs                     show database names

        show collections             show collections in current database

        show users                   show users in current database

        show profile                 show most recent system.profile entries wit

h time >= 1ms

        show logs                    show the accessible logger names

        show log [name]              prints out the last segment of log in memor

y, 'global' is default

        use <db_name>                set current database

        db.foo.find()                list objects in collection foo

        db.foo.find( { a : 1 } )     list objects in foo where a == 1

        it                           result of the last line evaluated; use to f

urther iterate

        DBQuery.shellBatchSize = x   set default number of items to display on s

hell

        exit                         quit the mongo shell

4. 创建数据库——直接Use 数据库名称即可,例如use test

5. 创建documentdb.unicorns.insert({name: 'demo', sex: 'm', weight: 70})   不用按照这个标准来插入,unicorns为collection的名字可以自己取,可以插入任意个filed的数据。每插入一条数据后会自动生成一个ObjectId,日期格式表示为new Date(1976, 6, 18, 18, 18)

6. 查询集合。

6.1 查询所有集合——db.unicorns.find()

6.2 根据某个关键字查询(相当于where子句)

6.2.1 等于db.unicorns.find({name:'demo',sex:'m'})

6.2.2 大于db.unicorns.find({weight:{$gt:60}})      $函数写在{}

6.2.3 $lt, $lte, $gt, $gte and $ne分别表示小于、小于等于、大于、大于等于、不等于

6.2.4 $exists用于表示field是否存在 db.unicorns.find({weight:{$exists:false}})

6.2.5 orand db.unicorns.find({$or:[{name:'demo'},{name:'aaa'}]})

6.2.6 查询某几个特定filed值 db.unicorns.find(null,{name:1,sex:1})

6.2.7 排序 1表示升序,-1表示降序 db.unicorns.find().sort({name:1})

6.2.8 db.unicorns.find().sort({weight: -1}).limit(2).skip(1) 

得到第二个和第三个。limit规定查询个数,skip规定忽略几个。

6.2.9 查询document数量 db.unicorns.count()

7. 删除数据——db.unicorns.remove() 

8. 更新数据

8.1 更新某符合条件数据db.unicorns.update({name: ’demo’}, {$set: {weight: 590}}) 

8.2 更新所有符合条件数据 db.unicorns.update({name: ’demo’}, {$set: {weight: 590},false,true})

db.collection.update( criteria, objNew, upsert, multi )
criteria : update的查询条件,类似sql update查询内where后面的
objNew   : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql  update查询内set后面的
upsert   : 这个参数的意思是,如果不存在update的记录,是否插入objNew,true 插入,默认是false,不插入。若存在更新,否则添加
multi    : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true, 把按条件查出来多条记录全部更新。

8.3 db.unicorns.update({name: 'Pilot'}, {$inc: {weight: -2}}) $inc增加或减少数字 

8.4 db.unicorns.update({name: 'Aurora'}, {$push: {loves: 'sugar'}}) $push增加数组元素 $pop减少数组元素

9. 索引

创建索引的方式 

db.unicorns.ensureIndex({name: 1}) 

删除索引的方式 

db.unicorns.dropIndex({name: 1})

 创建独立索引 

db.unicorns.ensureIndex({name: 1}, {unique: true}) 

创建联合索引 

db.unicorns.dropIndex({name: 1, vampires: -1})

10. 创建用户和角色

创建用户

db.addUser('root','123')

创建管理员用户

Use admin ——进入管理员

db.addUser(‘admin’,’admin’) —— 创建管理员用户

db.auth(‘admin’,’admin’) —— 授予管理员权限

 

 

 

JAVA - MONGODB

API文档的地址

http://api.mongodb.org/java/

官方入门地址

http://www.mongodb.org/display/DOCS/Java+Tutorial

 

1. 下载驱动包。 mongo-java-driver 

2. 获得连接流程。 创建Mongo对象,获得DB对象,通过DB对象获得DBCollection对象。

3. 通过DBCollection对象可以进行增删改查操作。

 

简单的增删改查代码:

package com.lhb.main;

 

import java.util.Date;

 

import com.mongodb.BasicDBObject;

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.DBCursor;

import com.mongodb.DBObject;

import com.mongodb.Mongo;

 

public class MongoTest

{

public static void main(String[] args)

{

try

{

// insert();

// getMemo();

// update();

delete();

getListMemo();

catch (Exception e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

/**

 * 获得一个collection的连接,类似获得一个DB中某一个的table

 * 

 * @param collectionName

 *            collection名称

 * @return

 * @throws Exception

 */

public static DBCollection getDBCollection(String collectionName) throws Exception

{

Mongo m = new Mongo("localhost", 27017);

DB db = m.getDB("mydb");

if (db.authenticate("root""123".toCharArray()))

{

System.out.println("auth success");

}

DBCollection coll = db.getCollection(collectionName);

return coll;

}

 

/**

 * 在memo这个collection中插入一个document

 * 

 * @throws Exception

 */

public static void insert() throws Exception

{

DBCollection coll = getDBCollection("memo");

BasicDBObject bo = new BasicDBObject();

// 存放JSON

bo.put("title""one meeting");

bo.put("place""one meeting");

bo.put("time"new Date());

coll.insert(bo);

}

 

/**

 * 获得第一个实例

 * 

 * @throws Exception

 */

public static void getMemo() throws Exception

{

DBCollection coll = getDBCollection("memo");

BasicDBObject bo = (BasicDBObject) coll.findOne();

System.out.println(bo);

}

 

/**

 * 获得Memo内所有实例

 * 

 * @throws Exception

 */

public static void getListMemo() throws Exception

{

DBCollection coll = getDBCollection("memo");

DBCursor cursor = coll.find();

 

while (cursor.hasNext())

{

DBObject bo = cursor.next();

System.out.println("title:" + bo.get("title") + " place:" + bo.get("place") + " time:" + ((Date) bo.get("time")).toLocaleString());

}

}

 

/**

 * 删除一个对象

 * 

 * @throws Exception

 */

public static void delete() throws Exception

{

DBCollection coll = MongoTest.getDBCollection("memo");

BasicDBObject bo = new BasicDBObject();

bo.put("title""two meeting");

// 找到并且删除

coll.findAndRemove(bo);

}

 

/**

 * 更新一个对象

 * 

 * @throws Exception

 */

public static void update() throws Exception

{

DBCollection coll = MongoTest.getDBCollection("memo");

BasicDBObject bo = new BasicDBObject();

bo.put("title""one meeting");

BasicDBObject bonew = new BasicDBObject();

bonew.put("title""two meeting");

// 找到并且更新

coll.findAndModify(bo, bonew);

}

}

 

原创粉丝点击