1.启动MongoDB报错:exception in initAndListen: 28663 Cannot start server
打开目录:D:\Tools\Mongodb\bin>mongod --dbpath=D:\Tools\Mongodb\data\db
报错信息:[initandlisten]exception in initandlisten:28663 Cannot start server.The default storage engine 'wireTiger' is not available with this build of mongod. Please specify a different storage engine explicitly,e.g. --storageEngine=mmapv1., terminating
解决方案:D:\Tools\Mongodb\bin>mongod --dbpath=D:\Tools\Mongodb\data\db --storageEngine=mmapv1
浏览器访问:http://localhost:27017/,访问正常.
新打开一个命令窗口,在cmd命令下打开MongoDB安装目录:
如:cd D:\Tools\Mongodb\bin
D:\Tools\Mongodb\bin>mongo
显示:
MongoDB shell version:3.2.6
connecting to:test
db.person.insert({"name":"jack","age":20});
db.person.insert({"name":"tom","age":25});
var value={"name":"test","age":23,"address":{"province":"guangdong","city":"shenzhen"},"sport":["running","bike"]};
db.person.insert(value);
value.name="9527";
value.age=40;
value.address={"province":"hongkong","city":"hongkong"};
value.sport=["ping-pong","swimming"];
db.person.insert(value);
3.Find操作:
find全部:
db.person.find();
find条件:
db.person.find({"name":"jack"});
db.person.findOne({"name":"9527"});
find条件(>,>=,<,<=,!=,=,or,in,nin):
db.person.find({"age":{$gt:20}});
db.person.find({"age":{$gte:20}});
db.person.find({"age":{$lt:30}});
db.person.find({"age":{$lte:30}});
db.person.find({"age":{$ne:40}});
db.person.find({$or:[{"age":40},{"age":20}]});
db.person.find({"name":{$in:["test":"9527"]}});
db.person.find({"name":{$nin:["test":"9527"]}});
正则表达式:
db.person.find({"name":/^t/,"name":/e$/});
JavaScript:
db.person.find({$where:fucntion(){return this.name == "test"}});
4.Update操作:
update整体:
var str=db.person.findOne({"name":"9527"});
str.age=35;
db.person.update({"name":"9527"},str);
update局部:
db.person.update({"name":"9527"},{$inc:{"age":20}});
db.person.update({"name":"9527"},{$set:{"age":10}});
upsert操作:
db.person.update({"name":"test_123"},{$inc:{"age":18}},true);
5.Remove操作:
remove全部:
db.person.remove();
remove条件:
db.person.remove({"name":"test_123"});
6.Count操作:
count全部:
db.person.count();
count条件:
db.person.count({"name":"test"});
7.Distinct操作:
db.person.distinct("age");
8.Group操作:
db.person.group({
"key":{"age":true},
"initial":{"person":[]},
"$reduce":function(cur,prev){
prev.person.push(cur.name);
}
});
db.person.group({
"key":{"age":true},
"initial":{"person":[]},
"$reduce":function(doc,out){
out.person.push(doc.name);
},
"finalize":function(out){
out.count=out.person.length;
},
"condition":{"age":{$lt:20}}
});
9.游标:
var list=db.person.find();
list.forEach(function(x){
print(x.name);
});
db.person.find().sort({"name":"test"}).skip(2).limit(2);
10.性能分析:explain
db.person.find({"name":"test"+10000}).explain();
11.建立索引:ensureIndex
db.person.ensureIndex({"name":1});
12.唯一索引
db.person.ensureIndex({"name":1},{"unique":true});
13.组合索引
db.person.ensureIndex({"name":1,"age":1});
14.删除索引
db.person.dropInexes("name");