文档查找中的计数值和 return 0 如果不存在 mongodb 聚合

Count value in a document lookup and return 0 if not exist mongodb aggregate

您好,我有以下合集

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
},

})

并且我想 return 计划在事务中出现的次数,并将其减少为我在计划集合中的对象项数组中拥有的总项数。 例如我有以下数据。

交易

  [
   {
      "_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,因为该计划尚未出现在事务中。

谢谢。抱歉我的英语不好。

  1. $lookup - 加入 schedule 集合 (_id) 与 transaction 集合 (schedule) 以获得 transactions数组。

  2. $project - 修饰输出文件。对于 total 字段,$subtract 对于 items.stock$sumtransactions 数组的 $size

db.schedule.aggregate([
  {
    "$lookup": {
      "from": "transaction",
      "localField": "_id",
      "foreignField": "schedule",
      "as": "transactions"
    }
  },
  {
    $project: {
      schedule: "$_id",
      total: {
        $subtract: [
          {
            $sum: "$items.stock"
          },
          {
            $size: "$transactions"
          }
        ]
      }
    }
  }
])

Sample Mongo Playground