我想更新我的Post模型上的一個欄位。Post 模型如下所示:
const postSchema = new Schema({
title: {
}
likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}],
upvotes: {
type: Number,
default: 0
}
})
我有一個資料庫posts,我想update通過計算他們likes(存盤的 ID)和檔案中的點贊數來計算update。upvotes有沒有辦法做到這一點?我可以使用Mongo shell.
uj5u.com熱心網友回復:
對于 Mongo 4.2 版,您可以使用流水線更新來執行此操作,如下所示:
db.collection.updateMany(
{},
[
{
$set: {
upvotes: {
$size: "$likes"
}
}
}
])
蒙戈游樂場
對于較小的 Mongo 版本,您必須將每個檔案讀入記憶體,并為其執行更新。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/456615.html
標籤:javascript mongodb 表示 猫鼬
