我有一个 mongo 文档,看起来像:
{
bookings: [
{complete: true, name: "John", checklist: {a: 1, b: 2}},
{complete: false, name: "Kate"},
{complete: true, name: "Mary", checklist: {a: 1, b: 2}}
]
}
我有一个带有投影的聚合,如下所示:
{
$project: {
'bookings.complete': 1,
'bookings.name': 1
}
}
它返回预订数组,只有完整和名称键。
我现在想添加一个键hasChecklist
,true
如果检查表存在,则称为键,false
否则。
但我被卡住了,因为这个投影总是会因为true
某种原因返回:(
{
$project: {
'bookings.complete': 1,
'bookings.name': 1
'bookings.hasChecklist': { $ne: ['$bookings.checklist', null] }
}
}
基本上我得到
{
bookings: [
{complete: true, name: "John", hasChecklist: true},
{complete: false, name: "Kate", hasChecklist: true},
{complete: true, name: "Mary", hasChecklist: true}
]
}
当我想要
{
bookings: [
{complete: true, name: "John", hasChecklist: true},
{complete: false, name: "Kate", hasChecklist: false},
{complete: true, name: "Mary", hasChecklist: true}
]
}
任何人都知道投影中的正确表达应该是什么?
试试$project
下面的:
{
"bookings": {
"$map": {
"input": "$bookings",
"as": "booking",
"in": {
"complete": "$$booking.complete",
"name": "$$booking.name",
"hasChecklist": { "$gt": [ "$$booking.checklist", null ] }
}
}
}
}
它应该返回以下结果:
{
"bookings" : [
{
"complete" : true,
"name" : "John",
"hasChecklist" : true
},
{
"complete" : false,
"name" : "Kate",
"hasChecklist" : false
},
{
"complete" : true,
"name" : "Mary",
"hasChecklist" : true
}
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句