How to get all fields of projection, if they doesn't exist in the collection?

Hey, I want to show all the document fields in the output but some of the fields are not present in some of the document then how can i display those fields with “NULL”. Here is the example:
Sample document:

/* 1 */
{
    "_id" : "1",
    "d" : 4.5,
    "c" : 1.1,
    "b" : "Nothing Special",
    "a" : false
} 
/* 2 */
{
    "_id" : "2",
    "a" : true
} 

Required Output:

{
        "_id" : "1",
        "d" : 4.5,
        "c" : 1.1,
        "b" : "Nothing Special",
        "a" : false
}
{
        "_id" : "2",
        "d" : null,
        "c" : null,
        "b" : null,
        "a" : true
}

Thanks in advance.

1 Like

The below query will help to get the desired output by using $ifNull.

db.getCollection("abcdef").aggregate(
    [
        
         { 
            "$project" : { 
                
                 "_id":1,
                 "a": { $ifNull: [ "$a", null ] },                                                     
                 "b":{ $ifNull: [ "$b", null ] },                                                     
                 "c":{ $ifNull: [ "$c", null ] },                                                     
                 "d":{ $ifNull: [ "$d", null ] }
                 
                 }	 
        }

    ]
);
2 Likes