执行查询聚合后,在mongoDB中显示字段文档



这是数据文档的一个示例

{
"_id" : ObjectId("5f437e7846103b2ad0fc5d7d"),
"order_no" : "O-200824-AGFJDQW",
"shipment_no" : "S-200824-AGWCRRM",
"member_id" : 2200140,
"ponta_id" : "9990010100280214",
"plu" : 14723,
"product_name" : "AQUA Air Mineral Botol Air Pet 600ml",
"qty" : 2,
"store_id" : "TD46",
"stock_on_hand" : 0,
"transaction_date" : ISODate("2020-08-24T08:28:29.931Z"),
"created_date" : ISODate("2020-08-24T08:46:48.441Z")
}

这是我运行的数据查询

var bulan = 12 //month is written with number. example: August = 8
db.log_stock_oos.aggregate([
{
$project: {
month: {
$month: '$transaction_date'
}
}
},
{
$match: {month: bulan}
}
]);

但运行查询后的结果是这样的

{
"_id" : ObjectId("5f44689607fe453fbfba433e"),
"month" : 12
}

如何使输出与我上面所附的文档显示完全一样??这是我的参考

当您使用投影时,如果您的值1包含该字段,则其类型为0,则从整个文档中排除该字段。投影

你可以做两件事

使用投影

db.collection.aggregate([
{
$project: {
month: {
$month: "$transaction_date"
},
order_no: 1,
shipment_no: 1,
member_id: 1,
//other fields like above with the value 1
}
},
// match stages
])

使用$addFields

在代码中使用$project的$addFields。如果您的文档中不存在,If将创建一个文件,否则它将覆盖字段