I need to a match aggregation query for this sample schema
{
"items": [
{name:'Test1'},{name: null}
]
}
Query1: get documents if all name is null or unassigned
Query2: get documents if at least 1 name is filled
I tried "addFields" with sum null count but i was wondering if there is a better way
2
Answers
You can use the
$elemMatch
and$ne
operators in the$match
stage of the aggregation pipeline to achieve the two queries you mentioned.The above aggregation pipeline returns all documents where all "name" values in the "items" array are null, and none of them are non-null.
The above pipeline matches documents where at least one element in the items array has a name value that is not null.
You can add more stages to the pipelines to further transform or project the matching documents as needed.
MongoDb store undefined as well but we can with with null as well.
because of if key exists it has null so we can match with null in both cases.
if key has some exists value then we can match with not equal to null then it
returns existed values from db
1. when we want data not (null or undefined) :
2. when we want data null or undefined :