Hi I'm new to the aggregation tool in mongoDB Compass and I've been playing around with queries on the database and have been trying to understand the documentation. I'm trying to do an analysis on database data that have a field 'totalAssets' and I'm trying to return the number of documents that have this 'totalAssets' field with it's value being a number type.
I've tried this query but I'm not sure if I'm headed in the right direction
There are a couple of things to note here. The first is that you have doubly nested curly brackets ({{
and }}
each pair on different lines) without anything in between, which is probably what is generating the Stage must be a properly formatted document
warning.
The other part is about how you actually filter for such documents. The $isNumber
aggregation operator that you point to could be used (by nesting it inside of a $expr
as demonstrated in this playground example), but there are alternative approaches as well. One such alternative would be to used $type
(playground link here):
db.collection.aggregate([
{
$match: {
totalAssets: {
"$type": "number"
}
}
}
])
Broadly speaking, it is worth keeping this in mind regarding using $match
:
The query syntax is identical to the read operation query syntax; i.e.
$match
does not accept raw aggregation expressions. Instead, use a$expr
query expression to include aggregation expression in$match
This is why the (aggregation expression) $isNumber
requires a wrapping $expr
in $match
(but not in other aggregation stages).