5

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

4
  • What do you mean "in MongoDB" - are you looking for an existing query that does this? Are you working in Node.js? And what is your overarching goal, are you trying to migrate data in your existing database so that your documents follow this new format or are you simply trying to modify the result of a query? Commented May 24, 2015 at 23:01
  • @WaiHaLee I've tried similar query as chridam suggested but I had a syntax error. Inattentive me. Commented May 24, 2015 at 23:15
  • @fettereddingoskidney I was trying to make a query for data correction in my db. Commented May 24, 2015 at 23:15
  • Cool man. Looks like you got it. Best of luck out there! Commented May 24, 2015 at 23:16

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.