MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

How can we add field in the output when we are using $replaceRoot in the query?

Here is the document:

   {
	"_id":1,
	"CID":"1",
	"a" : "Z",
	"b" : "Y", 
	"sign": [{
		"c": "c",
		"d": "d",
		"e": "e",
		"f": "insufficientFunds"
	}, {
		"g": false,
		"h": null,
		"i": 0,
		"j": "accessFunds"
	}],
	"y": null,
	"z": true
	
	}

Required Output:

/* 1 */
{
    "_id" : 1.0,
    "CID" : "1",
    "c" : "c",
    "d" : "d",
    "e" : "e",
    "f" : "insufficientFunds",
    "g" : null,
    "h" : null,
    "i" : null,
    "j" : null
}
/* 2 */
{
    "_id" : 1.0,
    "CID" : "1",
    "c" : null,
    "d" : null,
    "e" : null,
    "f" : null,
    "g" : false,
    "h" : null,
    "i" : 0.0,
    "j" : "accessFunds"
}

Here is the query

db.myColl.aggregate( [
 { 
            "$match" : { 
                "_id" : 1
            }
        },
   { $unwind: "$sign" },
   { $replaceRoot: { newRoot: "$sign" }},
 { 
            "$project" : { 
                "CID":1,
                "a" : 1,
                "b" : 1, 
                "y": 1,
                "z": 1,
                "c": 1,
		"d": 1,
		"e": 1,
		"f": 1,
      		"g": 1,
		"h": 1,
		"i": 1,
		"j": 1
          }
         }         
   ])

Output from the above query

/* 1 */
{
    "c" : "c",
    "d" : "d",
    "e" : "e",
    "f" : "insufficientFunds"
}

/* 2 */
{
    "g" : false,
    "h" : null,
    "i" : 0.0,
    "j" : "accessFunds"
}

I also used $addFields but it doesn’t work for me.

{ $addFields: { "CID": "$CID" } }

No need to use $replaceRoot. this will give required output.

db.myColl.aggregate( [
 { 
            "$match" : { 
                "_id" : 1
            }
        },
   { $unwind: "$sign" },
 { 
            "$project" : { 
                "CID":1,
                "c": { $ifNull: [ "$sign.c", null ] },                                                     
                "d":{ $ifNull: [ "$sign.d", null ] },                                                     
                "e":{ $ifNull: [ "$sign.e", null ] },                                                     
                "f":{ $ifNull: [ "$sign.f", null ] },
                "g": { $ifNull: [ "$sign.g", null ] },                                                     
                "h":{ $ifNull: [ "$sign.h", null ] },                                                     
                "i":{ $ifNull: [ "$sign.i", null ] },                                                     
                "j":{ $ifNull: [ "$sign.j", null ] }                
          }
         }         
   ])