Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Convert array to object

How I can convert an array to an 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"
    }
        ],
}

to this:

{
"_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 the ""userAddressList" : {..}".

like image 303
D. L. Avatar asked Sep 28 '22 20:09

D. L.


1 Answers

For MongoDB 4.2 and newer

You could try the following query which uses the aggregation pipeline in the update:

db.collection.updateMany(
    {},
    [
        { '$addFields': { 
            'userAddressList': { 
                '$arrayElemAt': ['$userAddressList', 0] 
            } 
        } }
    ]
)

For older MongoDB versions:

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

or use the aggregation framework where you run the following pipeline

db.collection.aggregate([
    { "$addFields": { 
        "userAddressList": { 
            "$arrayElemAt": ["$userAddressList", 0] 
        } 
    } },
    { "$out": "collection" }
])

Note that this does not update your collection but replaces the existing one and does not change any indexes that existed on the previous collection. If the aggregation fails, the $out operation makes no changes to the pre-existing collection.

like image 129
chridam Avatar answered Oct 07 '22 16:10

chridam