0

If have a collection of levels. A sample document looks like below:

{
    "_id" : ObjectId("5d89ccf8c3c948ac48e449fc"),
    "id" : 1,
    "name" : "option 1",
    "optionLevel" : [
        {
            "id" : 1,
            "deparmentId" : null,
            "name" : "level 1"
        },
        {
            "id" : 2,
            "deparmentId" : null,
            "name" : "level 2"
        }
    ]
}

How can I project a documentId inside optionLevel as empty string if its null?

Himanshu Sharma
  • 2,940
  • 1
  • 7
  • 18
Mahesh Bhatnagar
  • 1,042
  • 1
  • 7
  • 8

1 Answers1

0

The following query can get us the expected output:

db.collection.aggregate([
    {
        $addFields:{
            "optionLevel":{
                $map:{
                    "input":"$optionLevel",
                    "as":"info",
                    "in":{
                        $mergeObjects:[
                            "$$info",
                            {
                                "deparmentId":{
                                    $ifNull:["$$info.deparmentId",""]
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
]).pretty()

Data set:

{
    "_id" : ObjectId("5d89ccf8c3c948ac48e449fc"),
    "id" : 1,
    "name" : "option 1",
    "optionLevel" : [
        {
            "id" : 1,
            "deparmentId" : null,
            "name" : "level 1"
        },
        {
            "id" : 2,
            "deparmentId" : null,
            "name" : "level 2"
        }
    ]
}

Output:

{
    "_id" : ObjectId("5d89ccf8c3c948ac48e449fc"),
    "id" : 1,
    "name" : "option 1",
    "optionLevel" : [
        {
            "id" : 1,
            "deparmentId" : "",
            "name" : "level 1"
        },
        {
            "id" : 2,
            "deparmentId" : "",
            "name" : "level 2"
        }
    ]
}
Himanshu Sharma
  • 2,940
  • 1
  • 7
  • 18