Reputation: 2541
Im trying to exclude some fields from my booking aggregate.
{ "user":0, "paymentType":0, "_id":0 }
without this it works great, but with it I get the errors:
assert: command failed: {
"ok" : 0,
"errmsg" : "A pipeline stage specification object must contain exactly one field.",
"code" : 40323,
"codeName" : "Location40323"
} : aggregate failed
Is this possible to do, or can I only do it with find() ?
db.getCollection('booking').aggregate([{
$match: {
checkin : {$lte: (1512145439)},
checkout: {$gte: (1483203600)},
}
},
{
"user":0,
"paymentType":0,
"_id":0
}
, {
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "users"
}
}, {
$unwind: "$user"
}, {
$addFields: {
"country": "$users.country"
}
}, {
$project: {
"users": 0
}
}, {
$project: {
"booking": 0
}
}])
If I do like this, it will exclude the fields:
db.getCollection('booking').find({},
{
"user":0,
"paymentType":0,
"_id":0
})
Upvotes: 9
Views: 14213
Reputation: 1624
you can use $unset or $project
$unset and $project : The $unset is an alias for the $project stage that removes/excludes fields
{ $unset: [ "<field1>", "<field2>", ... ] }
{ $project: { "<field1>": 0, "<field2>": 0, ... } }//Return all but the specified fields
Upvotes: 7
Reputation: 75914
You've to use the field exclusion/inclusion inside the $project
stage in aggregation pipeline.
On a side note use $addFields
when you need to add new fields / overwrite fields and use $project
when you want to limit fields.
From the docs,
The $addFields stage is equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.
Upvotes: 3