插入操作
向集合(collection)中添加新的文档(document)。如果插入时集合不存在,自动创建该集合。db.my_collection.insert({})
db.my_collection.insertOne({})
db.my_collection.insertMany([])
删除操作
db.my_collection.deleteOne({})db.my_collection.deleteMany({})
db.my_collection.remove({},<justOne>),参数justOne=1或0
更新操作
修改集合中已经存在的文档。db.my_collection.update({条件},{更新操作}),完全更新,会改变BSON数据结构
db.my_collection.update({过滤条件},{$set:{<field>:<value>}},{multi:true}),$set,部分更新操作符
db.my_collection.updateOne()
db.my_collection.updateMany()
db.my_collection.replaceOne()
查询操作
从集合中读取文档,返回指向匹配文档的cursor对象。返回集合中的所有文档:
db.my_collection.find()或
db.my_collection.find({})
添加过滤条件
比较运算符等于 $gt $gte $lt $lte
返回集合中name="sunny"的所有文档:
db.my_collection.find({name:"sunny"})
逻辑运算符
AND(默认) 或OR:$or
查询name="sunny"并且age=20的所有文档
db.my_collection.find({name:"sunny",age:20})
查询name="sunny" 或者 age<20的所有文档
db.my_collection.find($or:[{name:"sunny"},{age:{$lt:20}}])
限定条件范围
$in $nin
查询name字段值为"sunny"或"tom"的所有文档
db.my_collection.find({name:{$in:["sunny","tom"]}})
使用正则表达式
查询name字段值中以"t"开头的所有文档
db.my_collection.find({name:{$regex:"^t"}})
或者
db.my_collection.find({name:/^t/})
自定义函数查询
查询name=="sunny"的所有文档
db.my_collection.find({$where:function(){return this.name=="sunny"}})
limit(num),限制返回文档数
db.my_collection.find().limit(2)
skip(offset),跳到第(offset+1)个文档开始查找
db.my_collection.find().skip(1)
分页: limit()与skip()结合使用
db.my_collection.find().skip(9).limit(10)
投影: 设置返回文档中字段的显示与隐藏。
通过传递第2个参数{<field>:<code>},code为1,则显示,为0,则隐藏。
db.my_collection.find({},{name:1})
排序:
对结果cursor使用sort({<field>:<code>}),code为1,升序,code为-1,降序。
db.my_collection.find().sort({age:1,name:-1})
统计文档数
db.<collection_name>.count({条件})
db.my_collection.count({age:{$gte:10}})
去除重复文档
db.<collection_name>.distinct("去重字段",{去重条件})
db.my_collection.distinct("name",{})