增
//增 create
user.create({
userName : "afeifei",
password : "123456"
});
删
user.deleteOne({userName:"afeifei"}).catch(err=>{if(err)throw err});
改
两个参数 第一个参数是查询条件,第二个是修改字段
- updateOne()
修改满足条件的第一个
如修改user等于hx的年纪改为30
userDB.updateOne({user:hx},{age:30})
.then(()=>{})
.catch(e=>{
console.log(e);
})
- updateMany()
修改满足条件的所有
{password:"456"} 修改 password 为"456"
{$set:{"userInfo.test":"123"}} 修改 userInfo.test 为"123"
{$inc:{age:1}} 修改 age 自增1
{$unset:{age:0}} 移除 age 属性(值随便写啥都是移除)
{$push:{arr:999}} 为 arr数组 添加一条 999 值
{$push:{arr: {$each:[1,4,5,9],$slice:-5}}} 为 arr数组 添加 1 4 5 9 值,并截取倒数5个
{$addToSet:{arr:20}} 为 arr数组 添加一条 20 值,如果20存在,则不添加
{$pop:{arr:1}} 删除 arr数组 的最后一项,arr值为-1则删除第一项
{$pull:{arr:123}} 删除 arr数组 所有123值
查
-
find()
4个参数- 1conditions 查询条件
$or $nor 或者 或者取反,eg: {$or:[{name:"afei"},{age:"20"}]}
$gt $gte $lt $lte $ne 大于 大于等于 小于 小于等于 不等于,eg: {age:{$lt:20}}
$in $nin 在/不在 指定的多个字段之类,eg: {name:{$in:["afei","zhuque"]}}
$exists 存在某属性,eg: {age:{$exists:true}}
$size 数组长度匹配,eg: {arr:{$size:2}}
$all 数组中是否存在指定的所有项,eg: {arr:{$all:[123,456]}}
$where 可以使用JavaScript代码或函数,eg: {$where:"this.age===18"}
正则 使用正则匹配,eg: {name:/afei/}
- 2projection 返回内容选项
projection 返回内容选项
默认全部显示,
{age:1} 只显示age属性和_id属性
{age:1,_id:0} 只显示age属性
第二个参数,展示的内容 1为显示,2为隐藏
projection
userDB.find({},{user:1,_id:0}).then((msg)=>{
console.log(msg); //
})
- 3options 查询配置选项
options 查询配置选项
常用skip limit sort
{skip:2} 略过前2条数据
{limit:5} 最多返回5条属性
{sort:{age:1}} 按照age项升序排列
如跳过前两条数据显示两条
userDB.find({},{},{
skip:2,
limit:2
}).then((msg)=>{
console.log(msg);
})
-
4callback
回调函数,参数err data,可用Promise代替
找到pass为123456的相关信息
userDB.find({
pass:"123456"
}).then((msg)=>{
console.log(msg); //结果在.then里面
})
findone
- findOne()
会查找到满足条件的第一条数据
userDB.findOne({
pass:"123456"
}).then((msg)=>{
console.log(msg); //结果在.then里面
})
findOne
查找不到就是
null
- findById()
通过数据中每条数据自带的_id值来查找














网友评论