skip to Main Content

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


  1. You can use the $elemMatch and $ne operators in the $match stage of the aggregation pipeline to achieve the two queries you mentioned.

    For Query1, the $elemMatch operator is used to match documents where at least one array element satisfies the specified condition. In this case, it checks if any "name" value in the "items" array is not equal to null, and the $not operator negates the condition to match documents where all "name" values are null. Here’s an example aggregation pipeline:

    db.collection.aggregate([
      {
        $match: {
          "items": { $not: { $elemMatch: { "name": { $ne: null } } } }
        }
      }
    ])
    

    The above aggregation pipeline returns all documents where all "name" values in the "items" array are null, and none of them are non-null.

    For Query2, you can use the $elemMatch operator to match documents where at least one element in the items array has a non-null name value. Here’s an example aggregation pipeline:

    db.collection.aggregate([
      {
        $match: {
          "items": { $elemMatch: { "name": { $ne: 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.

    Login or Signup to reply.
  2. 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) :

     db.collection.aggregate([
      {
        "$unwind": "$items"
      },
      {
        $match: {
          "items.name": {
            $ne: null
          }
        }
      }
    ])
    

    2. when we want data null or undefined :

        db.collection.aggregate([
      {
        "$unwind": "$items"
      },
      {
        $match: {
          "items.name": {
            $eq: null
          }
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search