你好我有以下收藏
const TransactionSchema = mongoose.Schema({
schedule: {
type: mongoose.Schema.ObjectId,
required: true,
ref: "Schedule"
},
uniqueCode: {
type: String,
required: true
},
created: {
type: Date,
default: Date.now
},
status: {
type: String,
required: false
},
})
const ScheduleSchema = mongoose.Schema({
start: {
type: Date,
required: true,
},
end: {
type: Date,
required: false,
},
questions: {
type: Array,
default: [],
},
items: [{
item: {
type: mongoose.Schema.ObjectId,
require: true,
ref: "Item"
},
stok: {
type: Number,
required: true
}
}],
status: {
type: String,
required: false
},
})
我想回傳計劃在事務中出現的次數,并用我在計劃集合中的物件專案陣列中的總專案數來減少它。例如我有以下資料。
交易
[
{
"_id":"identifier",
"schedule":identifier1,
"uniqueCode":"312312312312",
"created":"Date"
},
{
"_id":"identifier",
"schedule":identifier1,
"uniqueCode":"1213123123",
"created":"Date"
}
]
日程
[
{
"_id":identifier1,
"start":"date",
"end":"date",
"questions":[
12,
32,
122
],
"items":[
{
"item":itemIdentifier1,
"stock":120
},
{
"item":itemIndentifier2,
"stock":1000
}
],
"status":"Active"
},
{
"_id":identifier2,
"start":"date",
"end":"date",
"questions":[
12,
32,
122
],
"items":[
{
"item":itemIdentifier1,
"stock":120
}
],
"status":"Active"
}
]
我想得到以下結果:
[
{
"schedule":identifier1,
"total":1118
},
{
"schedule":identifier2,
"total":120
}
]
注意:第一行顯示專案 1120 - 2 的總庫存中的 1118,這是計劃在事務中出現的次數。第二行顯示 120,因為計劃尚未出現在事務中。
謝謝你。對不起,我的英語不好。
uj5u.com熱心網友回復:
$lookup-將schedule集合 (_id) 與transaction集合 (schedule) 連接以獲取transactions陣列。$project- 裝飾輸出檔案。對于total欄位,對于$subtract陣列$sum和陣列。items.stock$sizetransactions
db.schedule.aggregate([
{
"$lookup": {
"from": "transaction",
"localField": "_id",
"foreignField": "schedule",
"as": "transactions"
}
},
{
$project: {
schedule: "$_id",
total: {
$subtract: [
{
$sum: "$items.stock"
},
{
$size: "$transactions"
}
]
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/465220.html
