MongoDB: convert array to object

How can I convert array to object in MongoDB?

For example, I want to convert this document:

{
"_id" : NumberLong(279),
"userAddressList" : [ 
    {
        "street" : "Street",
        "house" : "House",
        "building" : "Building",
        "flat" : NumberLong(0),
        "entrance" : NumberLong(0),
        "floor" : NumberLong(0),
        "intercom" : "Intercome"
    }
        ],
}

      

:

{
"_id" : NumberLong(279),
"userAddressList" :
    {
        "street" : "Street",
        "house" : "House",
        "building" : "Building",
        "flat" : NumberLong(0),
        "entrance" : NumberLong(0),
        "floor" : NumberLong(0),
        "intercom" : "Intercome"
    },
}

      

So I need to convert ""userAddressList" : [{..}]"

to ""userAddressList" : {..}"

.

+3


source to share


1 answer


You can try the following query:



db.collection.find().forEach(function(doc){
    userAddressList = doc.userAddressList[0];
    doc.userAddressList = userAddressList;
    db.collection.save(doc);
})

      

+1


source







All Articles