N
N
neuroepoc2018-03-07 21:46:04
Python
neuroepoc, 2018-03-07 21:46:04

How to add records in mongodb only if they don't exist?

import pymongo
...
DATA=[{'title': 'sTitle1', 'info': 'sInfo1'}, {'title': 'sTitle2', 'info': 'sInfo2'}]
...
db = client.get_default_database()
yamaha = db['yamaha']
yamaha.insert_many([DATA])
...
DATA2=[{'title': 'sTitle3', 'info': 'sInfo3'}, {'title': 'sTitle2', 'info': 'sInfo2'}]

how to add DATA2 array to yamaha so that after that yamaha has only 3 entries?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Zakharov, 2018-03-11
@neuroepoc

Here we compare by specific field

for item in DATA2:
    yamaha.update({'title': item['title']}, {'$set': item}, upsert=True)

If you want to compare across the entire document
for item in DATA2:
        search_result = yamaha.find_one(item)
        if search_result is None:
            yamaha.insert(item)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question