JPG
JPG

Reputation: 1253

move or shift elements in mongo to other json element

I needed to move all timestamp elements/field of my collection to jsonObject element in MongoDB. Is there a query or function to do so.. Below is a sample of document:

{
    "_id" : ObjectId("5ca307e333ad6127e0ddbe40"),
    "_class" : "com.google.mongo.docs.IvrMongoLog",
    "jsonObject" : {
        "message" : [ 
            {
                "time" : "03:00:23",
                "action" : "call ended succesfully ",
                "user_input" : "user hangup the call",
                "language" : "en"
            }
        ],
        "msisdn" : "89######66"
    },
    "timestamp" : "2019-06-01 12:00:00:00"
}

here I want to move timestamp element to inside of jsonObject. something like this:

{
    "_id" : ObjectId("5ca307e333ad6127e0ddbe40"),
    "_class" : "com.google.mongo.docs.IvrMongoLog",
    "jsonObject" : {
        "message" : [ 
            {
                "time" : "03:00:23",
                "action" : "call ended succesfully ",
                "user_input" : "user hangup the call",
                "language" : "en"
            }
        ],
        "msisdn" : "89######66",
        "timestamp" : "2019-06-01 12:00:00:00"
    }
}

Upvotes: 1

Views: 74

Answers (1)

mickl
mickl

Reputation: 49945

You can use $rename

db.col.updateMany({}, { $rename: { 'timestamp': 'jsonObject.timestamp' } }

Upvotes: 2

Related Questions