BSM
BSM

Reputation: 183

MongoDB : Push data to a map

I have employee json as below in db, I want to create a map of "addressId"(key) and "city"(value) and return the result.

{
    "_id" :1,
    "_class" : "com.entity.Employee",
    "clientId" : 1,
    "addresses" : [ 
        {
            "addressId" : 1,
            "street" : "ghi",
            "city" : "Hyderabad"
        }, 
        {
           "addressId" : 2,
            "street" : "abc",
            "city" : "Bangalore"
        }, 
        {
            "addressId" : 3,
            "street" : "def",
            "city" : "Chennai"
        }
    ]
}

Please suggest me which operator can I use and whether this can be achieved using $project.

Upvotes: 0

Views: 367

Answers (1)

Gyaneshwar Pardhi
Gyaneshwar Pardhi

Reputation: 471

Yes you have to use projection with unwind and forEach to make key value pair

try below mongo query

db.collection_name.aggregate([{"$unwind":"$addresses"},{"$project": {"addressId": "$addresses.addressId", "city":"$addresses.city", "_class":"$_class","clientId":"$clientId"}     }]).forEach(function(ojb){ojb[ojb.addressId]=ojb.city; printjson(ojb);});

Upvotes: 1

Related Questions