Make use of aggregation pipeline.
Solution -
db.test.aggregate([
{ $unwind: "$mappinginfo" },
{ $project: {
dealer_code: 1,
territory: "$mappinginfo.territory",
area: "$mappinginfo.area",
zone: "$mappinginfo.zone",
active: 1
}}
]);
Explanation
Aggregation pipeline as the name is, works on data in pipeline. A pipeline has an input, an operator and an output. For the example above -
- First stage is an unwind stage which will be fed with an entire collection. The unwind operator will iterate on individual documents and for each document it will create as many copies as are elements in mappinginfo field. For your case it will only create just one copy. After the unwind stage the resulting document would look like this -
[{
"_id" : ObjectId("5e311e8bb94999f1be0d5ead"),
"dealer_code" : "123",
"mappinginfo": {
"territory" : "MORADABAD",
"area" : "UPH",
"zone" : "N"
}
"active" : NumberInt(1),
}]
Notice that the mappinginfo is no more a list.
- Next stage is a projection stage. $project operator will simply take the above list of documents as input and for each document either it will simply project the field as it is or will change the value of the field based on what is available in the current document.
{ "active": 1 } implies projecting the value as it is. { "zone": "$mappinginfo.zone" } implies projecting the value of zone inside mappinginfo field under the name zone at the root level.
More info on both operators -
- $unwind
- $project