[英]Difference between db.find and db.aggregate in Mongo Nodejs
我想知道 db.find 中的 output 和 MongoDB 中的 db.aggregate 之間有什么區別嗎?
我正在使用 Nodejs 從 Mongo DB 查詢一些數據,當前的實現是:
Document.find(
{ userid: mongoose.Types.ObjectId(userId) },
{
'_id':1,
'name':1,
'size':1,
})
但我想用數據庫中的值計算 go 的大小,所以我知道我不能更改查找查詢中的值,所以我必須使用聚合:
Document.aggregate([
{$match:{userid: mongoose.Types.ObjectId(userId), isDeleted: deleted }},
{$project:{
'_id':1,
'name':1,
'size': {$size: "$followers"}
}}
])
現在,兩個查詢都給出了相同的結果,我還使用 typeof() 檢查了數據類型,兩者都返回 object。
但是當聚合 function 的結果返回時,它會在我使用 map 的另一個 function 上拋出一些錯誤。
document = await Promise.all(document.map(async(doc) => {
let followerData
if (doc.size > 0) {
const icon = await getIcon(doc.name)
if (icon){
followerData = {
socialIcon: icon,
name: name,
}
}
}
return { ...doc._doc, followerData }
}))
現在,這個 function 可以使用 find 但不能使用聚合,它只添加 followerData 並刪除從 db 獲取的現有數據。 不知道這里發生了什么。 任何人都可以幫助我嗎?
模式:
var socialSchema = new Schema({
userid: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
required: true,
},
name: { type: String, max: 255 },
followers: [
{
name: { type: String },
handle: { type: String },
},
],
size: {
type: Number,
default: function() {
return this.followers.length
},
}
})
聚合的主要目的是簡化對大量條目的查詢並生成少量對您有價值的結果。
您還可以使用多個查找查詢,但請記住您不能使用查找查詢創建新字段。 另一方面,$group 階段允許您定義新字段。
如果您的查詢很復雜,例如添加新字段或匯總字段或比較字段等,您可以使用聚合。 這將花費更多時間,但效果會比 find 更好。
有關更多詳細信息,您可以關注此鏈接Aggregation vs Find
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.