Reputation: 481
I have a mongo document that looks something like:
{
bookings: [
{complete: true, name: "John", checklist: {a: 1, b: 2}},
{complete: false, name: "Kate"},
{complete: true, name: "Mary", checklist: {a: 1, b: 2}}
]
}
I have a aggregation with a projection that looks like:
{
$project: {
'bookings.complete': 1,
'bookings.name': 1
}
}
Which returns the array of bookings, with only the complete and name keys.
I now want to add a key called hasChecklist
that is true
if the checklist exists, and false
otherwise.
But I'm stuck because this projection will always return true
for some reason :(
{
$project: {
'bookings.complete': 1,
'bookings.name': 1
'bookings.hasChecklist': { $ne: ['$bookings.checklist', null] }
}
}
Basically I get
{
bookings: [
{complete: true, name: "John", hasChecklist: true},
{complete: false, name: "Kate", hasChecklist: true},
{complete: true, name: "Mary", hasChecklist: true}
]
}
When I want
{
bookings: [
{complete: true, name: "John", hasChecklist: true},
{complete: false, name: "Kate", hasChecklist: false},
{complete: true, name: "Mary", hasChecklist: true}
]
}
Anyone know what the correct expression in the projection should be?
Upvotes: 1
Views: 1257
Reputation: 785
Try the $project
below:
{
"bookings": {
"$map": {
"input": "$bookings",
"as": "booking",
"in": {
"complete": "$$booking.complete",
"name": "$$booking.name",
"hasChecklist": { "$gt": [ "$$booking.checklist", null ] }
}
}
}
}
It should return the following result:
{
"bookings" : [
{
"complete" : true,
"name" : "John",
"hasChecklist" : true
},
{
"complete" : false,
"name" : "Kate",
"hasChecklist" : false
},
{
"complete" : true,
"name" : "Mary",
"hasChecklist" : true
}
]
}
Upvotes: 2