插入记录:
db.books.insert(book);
查询记录:
db.books.find({},{title:1});
参数:查询条件、希望返回的字段(其中1,0表示ture,false)
db.books.find({},{title:1, _id:0});//不显示id的字段
示例:
1.查询全局:
db.books.find()
2.条件查询:
db.books.find({author:”Alan”});
更新对象:
db.books.update({},{$set:{“keywords”:[]}},false,true);
参数:搜索条件、更新对象、upsert更新插入(存在更新,不存在插入)、多重更新(更新多个对象)
追加内容更新:
db.books.update({author: “Alan"},{$push:{“keywords”:”developer"}});
在搜索的对象的keywords中拼接一个新的字符串
诊断:
db.books.find().explain();
对于频繁使用的查询,赢避免使用BasicCursor,通过添加索引使用BtreeCursor。
添加索引:
db.books.ensureIndex({author:1});
分组查询统计:
map & reduce
map = function(){
emit(this.author, 1);
}
reduce = function(key, values){
var total = 0;
values.forEach(function(value){
total += value;
})
}
db.books.mapReduce(map, reduce, {out: ”bookoutput"});
查询更新:
查询的同时执行更新,添加版本号机制,防止并发修改
db.books.findAndModify({
query:{“_id”:123, version:1},
update:{$set: {version:2}}
});
db.books.insert(book);
查询记录:
db.books.find({},{title:1});
参数:查询条件、希望返回的字段(其中1,0表示ture,false)
db.books.find({},{title:1, _id:0});//不显示id的字段
示例:
1.查询全局:
db.books.find()
2.条件查询:
db.books.find({author:”Alan”});
更新对象:
db.books.update({},{$set:{“keywords”:[]}},false,true);
参数:搜索条件、更新对象、upsert更新插入(存在更新,不存在插入)、多重更新(更新多个对象)
追加内容更新:
db.books.update({author: “Alan"},{$push:{“keywords”:”developer"}});
在搜索的对象的keywords中拼接一个新的字符串
诊断:
db.books.find().explain();
对于频繁使用的查询,赢避免使用BasicCursor,通过添加索引使用BtreeCursor。
添加索引:
db.books.ensureIndex({author:1});
分组查询统计:
map & reduce
map = function(){
emit(this.author, 1);
}
reduce = function(key, values){
var total = 0;
values.forEach(function(value){
total += value;
})
}
db.books.mapReduce(map, reduce, {out: ”bookoutput"});
查询更新:
查询的同时执行更新,添加版本号机制,防止并发修改
db.books.findAndModify({
query:{“_id”:123, version:1},
update:{$set: {version:2}}
});