Append item to Mongo Array
NickName:Mike Ask DateTime:2020-07-10T07:00:31

Append item to Mongo Array

I have a mongodb document I am trying to update. This answer was helpful, but every time I insert into the database, the data is inserted as an array inside of the array whereas I just want to insert the object directly into the array.

Here is what I am doing.

# My function to update the array
def append_site(gml_id, new_site):
    col.update_one({'gml_id': gml_id}, {'$push': {'websites': new_site}}, upsert = True)
# My Dataframe
data = {'name':['ABC'], 
        'gml_id':['f9395e09'],
        'url':['ABC.com']
        }
df = pd.DataFrame(data)

# Grouping data for upsert
df = df.groupby(['gml_id']).apply(lambda x: x[['name','url']].to_dict('r')).reset_index().rename(columns={0:'websites'})
# Apply function to every row
df.apply(lambda row: append_site(row['gml_id'], row['websites']), axis = 1)

Here is the outcome:

{
    "gml_id": "f9395e09",
    "websites": [
        {
            "name": "XYZ.com",
            "url": "...xyz.com"
        },
        [
            {
                "name": "ABC.com",
                "url": "...abc.com"
            }
        ]
    ]
}

Here is the goal:

{
    "gml_id": "f9395e09",
    "websites": [
        {
            "name": "XYZ.com",
            "url": "...xyz.com"
        },
        {
            "name": "ABC.com",
            "url": "...abc.com"
        }
    ]
}

Copyright Notice:Content Author:「Mike」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62824967/append-item-to-mongo-array

Answers
Belly Buster 2020-07-10T07:56:44

Your issue is that the websites array is being appended with a list object rather than a dict, i.e. new_site is a list.\nAs you haven't posted where you call append_site(), this is a litle speculative, but you could try changing this line and seeing if it gives the effect you need.\ncol.update_one({'gml_id': gml_id}, {'$push': {'websites': new_site[0]}}, upsert = True)\n\nAlternatively make sure you are passing a dict object to the function.",


More about “Append item to Mongo Array” related questions

Append item to Mongo Array

I have a mongodb document I am trying to update. This answer was helpful, but every time I insert into the database, the data is inserted as an array inside of the array whereas I just want to inse...

Show Detail

How to prepend an array and remove dupes in Mongo?

In MongoDB, what is a good way to prepend an item to an array, and remove any duplicate items? $addToSet does not do anything if the item is already in the array. This SO question shows two ways of

Show Detail

append field value in inline json array object in mongo through kafka mongo sink connector

publish first insertion : {"Customer_id": 2, "transaction_id": "1", "idd": [999, 1111], "id": 1} and then second one : {"Customer_id": 2, "transaction_id": &

Show Detail

How to append an item to an array in DynamoDB

Hi im trying to append an item to a dynamoDB array. exports.handler = (event,context,callback)=>{ let params = { Key:{ "userName":event.userName, }, UpdateExpression:&

Show Detail

Pull item by value from embedded array in Mongo

I want to pull a specific item from an embedded array...assume the following mongo document.... db.test.find() { id:1, comments : [ { cid: 1 }, { cid: 2 }, { cid: 3 }, ...

Show Detail

how to append information to a document in mongo?

Background Information I have the following data in my mongo database: { "_id" : ObjectId("581c97b573df465d63af53ae"), "ph" : "+17771111234", "fax&quo

Show Detail

Get dict from Mongo and convert to ndarray using Numpy

I have an aggregate query in Mongo that returns data like: {a: 1, b: 2, c: 3} {a: 4, b: 5, c: 6} {a: 7, b: 8, c: 9} I would like to do an FFT for a, b and c and I need to put the data in 3 numpy ...

Show Detail

In Mongo, map over array and update docs

I am trying to update multiple docs in mongo. I have an array, and I want to update multiple mongo docs with a specific object from that array. let items = [{ order: 0 }, { order: 1 }, { order: 2...

Show Detail

Mongo push to array inside array

im new with mongo and so far have no issue using it. Until i stuck at this. I need to push a document to an array inside an array. Can refer to json below. { 'user_id':'{1231mjnD-32JIjn-3213}'...

Show Detail

how to append data in mongo db using rails

I am using rails 4.1.8 along with ruby 2.1.2p95 and mongo-2.0.4 gem to connect to mongo db v3.0.3. I have read this document but it doesn't provide how do we append the data in the existing row ...

Show Detail