I have a mongodb collection . When I do.
db.bill.find({})
I get,
Mongo 3.4+ has $addFields aggregation stage, which allows you to avoid explicitly listing all the other fields in $project:
db.bill.aggregate([
{"$addFields": {
"bill_codes": {"$setUnion": ["$bill_codes", []]}
}}
])
Just for reference, here is another (more lengthy) way that uses replaceRoot and also doesn't require listing all possible fields:
db.bill.aggregate([
{'$unwind': {
'path': '$bill_codes',
// output the document even if its list of books is empty
'preserveNullAndEmptyArrays': true
}},
{'$group': {
'_id': '$_id',
'bill_codes': {'$addToSet': '$bill_codes'},
// arbitrary name that doesn't exist on any document
'_other_fields': {'$first': '$$ROOT'},
}},
{
// the field, in the resulting document, has the value from the last document merged for the field. (c) docs
// so the new deduped array value will be used
'$replaceRoot': {'newRoot': {'$mergeObjects': ['$_other_fields', "$$ROOT"]}}
},
{'$project': {'_other_fields': 0}}
])