$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:
new:bool - 如果爲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();