我有一个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}
]
}
任何人都知道投影中的正确表达应该是什么?
答案 0 :(得分:2)
尝试下面的$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
}
]
}