mongoose非常好用但易忘的API

$unset删除document指定字段

db.user.update(
{"account":{"$exists":true}},
{"$unset":{"account":""}},
{multi:true}
);

findOneAndUpdate()

A.findOneAndUpdate(conditions, update, options, callback) // executes
//伪代码
A.findOneAndUpdate({},{},{new:true,upsert:true,fileds:{"name":1,"email":1}},callback)

//parameter options:
newbool - 如果为true,则返回修改过的文档而不是原始文档。默认为false(在4.0中更改)
upsert:bool - 创建对象,如果它不存在。默认为false。
fields:{Object | String} - 字段选择。相当于.select(fields).findOneAndUpdate()
maxTimeMS:对查询设置时间限制 - 要求mongodb> = 2.6.0
sort:如果条件找到多个文档,请设置排序顺序以选择要更新的文档
runValidators:如果为true,则在此命令上运行更新验证程序。更新验证器根据模型的模式验证更新操作。
setDefaultsOnInsert:如果这upsert是真的,如果创建了新文档,Model将应用模型模式中指定的默认值。该选项仅适用于MongoDB> = 2.4,因为它依赖于MongoDB的$setOnInsert操作符。
rawResult:如果为true,则返回MongoDB驱动程序的原始结果
strict:覆盖此更新的模式的严格模式选项

*注意***findOneAndUpdate 和Update在mongooose中 只有声明的schema中具体的属性才会生效

聚合函数 Aggregate

$project:包含、排除、重命名和显示字段

$match:查询,需要同find()一样的参数

$limit:限制结果数量

$skip:忽略结果的数量

$sort:按照给定的字段排序结果

$group:按照给定表达式组合结果

$unwind:分割嵌入数组到自己顶层文件

------------------------------------------------------
document经过$group之后,系统会为其生成一个新的document

db.zipcodes.aggregate(  
    {$group:{_id:{state:"$state",city:"$city"}, totalPop:{$sum:"$pop"}}},//统计州的所有人,生成一个新的文档,是关于州与其总人口  
    {$sort:{"totalPop":-1}},//对新文档,根据人口数倒序排序  
    {$group:{_id:"$_id.state",  
        "biggestCity":{$first:"$_id.city"},//最大人口的城市  
        "biggestPop":{$first:"totalPop"},//最大人口的数量  
        "smallestCity":{$last:"$_id.city"},  
        "smallestPop":{$last:"totalPop"}  
    }},//重新组成一个新的文件,包含,州名,最大人口数和最小人口数  
    //本来结构到此基本上差不多了  
    //但我们需要再对数据进行格式化  
    {$project:  
        {_id:0,  
        state:"$_id",  
        biggestCity:{name:"$biggestCity",pop:"$biggestPop"},  
        smallestCity:{name:"$smallestCity",pop:"$smallestPop"}        
        }  
    }  
);
具体事例参考 https://blog.csdn.net/moqiang02/article/details/39544617

findOne()和Save()返回的对象 属性不能更改的处理方式

let _obj=await Model.findOne({});
//此时_obj对象不能添加属性也不能删除属性

//解决方案
let _obj=await Model.findOne({}).lean();

let _obj=await Model.save();
//此时_obj对象不能添加属性也不能删除属性
_obj=_obj.toObject();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章