mongodb的一些简单操作

mongo 使用

mongod 开机
mongod --dbpath c:mongo

mongod --storageEngine mmapv1 --dbpath c:mongo

mongoimport 导入数据
mongoimport --db ts --collection student --drop --file D:1.json
--db test 想往哪个数据库里导入
--collection testaurants想往哪个集合中导入
--drop把集合清空
--file primer-dataset.json哪个文件

show dbs列出数据库所有

使用数据库
use 数据库名

db查看当前数据库

新建数据库
use一个不存在的就是新建

db.student.insert({'':''})插入数据
db.student.find()查找数据
db.student.find({})

db.dropDatabase()删除数据库,删除当前所在的

db.student.update({'name':'wo'},{$set:{'age':16}});修改数据

db.student.remove({'name':'wo'});删除数据

db.student.stats().count;查询总数

db.student.createIndex({'name':1})创建索引

db.student.createIndex({'name':1},{unique:true})索引不能相同


db.posts.drop()删除表

$push 插入数据的三种方法
db.liuyan.update({"username" : "11"},{$push:{'www':'1111','qqq':'2222','eee':'444'}})

db.liuyan.update({"username" : "11"},{ $push: { liuyan: { $each: [ 90, 92, 85 ] } } } )

db.liuyan.update({"username":"11"},{$push:{liuyan:{$each:[{"wk":1,"score":10},{"wk":1,"score":10}]}}})
//$sort: 排列顺序
//$slice: 一共的个数

db.liuyan.update({"username":"11"},{$push:{liuyan:{$each:[{"wk":1,"score":10},{"wk":1,"score":10}],$sort: { score: -1 }, $slice: 3}}})


查找内嵌文档

{
"_id" : ObjectId("5a432d2bd39fd51ba0537e53"),
"username" : "admin",
"content" : "diertiao",
"wzid" : "5a41e936bc08173510061fca",
"time" : "2017-12-27 13:18:35",
"huifu" : "",
"liuyan" : [
{
"username" : "11",
"user" : "admin",
"wztitle" : "第一篇",
"type" : "admin",
"content" : "哈哈",
"wzid" : "5a41e936bc08173510061fca",
"time" : "2017-12-27 13:35:40"
}
]
},

db.liuyan.find({"liuyan.type":"11"})

db.liuyan.find({"liuyan":{"$elemMatch" : {"type" : "11"}}})

//更新内嵌数据
db.demo.update({"people_id":"2", "albums.id":"2"}, { $set : {"albums.$.name":"6" }})只能更新第一个

//获取内嵌文档的长度
db.liuyan.aggregate([{$project:{lenOfArray: {$size:"$liuyan"}}}]).next().lenOfArray


//根据条件删除内嵌数组指定字段
db.posts.update({"username":"11"},{$pull:{"shoucang":{"username":"11"}}})

//游标
var cursor=db.liuyan.find();
cursor.forEach(function(x){print(x.liuyan.length)});
//找出所有内嵌文档
db.liuyan.distinct("liuyan")