daiyue
daiyue

Reputation: 7448

pymongo - how to append values to array?

I am trying to create a database if it is not there already in mongo, and then create a collection in the database; then insert/update a document (which contains two keys, called erp and dataset whose value is a list of strings) in the collection. I know how to upsert a document like,

self.connection = pymongo.MongoClient(host=db_host, port=db_port)
self.connection.datasets.datasets.update_one({'erp': 'erp1'},
                                             {'$set': {'data_set': ['database1']}},
                                             upsert=True)

When the document is inserted into mongo for the 1st time, create a list with string(s) as values for the field 'data_set', but how to maintain/update the list of strings that whenever a new string comes in, just append the existing list for data_set.

UPDATE. The working query

connection.erp_datasets.erp_datasets.update_one({'erp_name': 'erp1'},
                                                {'$push': {'data_set': 'database1'}}, upsert=True)

Upvotes: 0

Views: 4635

Answers (1)

Rehan Manzoor
Rehan Manzoor

Reputation: 2743

I think what you're looking for a $push update operator.

The $push operator appends a specified value to an array.

self.connection.datasets.datasets.update_one(
   {'erp': 'erp1'},
   {'$push': {'data_set': 'database1'}}
)

Upvotes: 3

Related Questions