Tuesday, 21 February 2023

How do I upsert a document in MongoDB using mongoengine for Python?

I'm having a hard time struggling how to find out how to upsert in MongoDB using mongoengine.

My current inserting code looks like this:

for issue in data['issues']:

    doc = Issue(
        key=issue['key'],
        title=issue["fields"]["summary"],
        type=issue["fields"]["issuetype"]["name"],
        status=issue["fields"]["status"]["name"],
        assignee=issue["fields"]["assignee"]["displayName"] if issue["fields"]["assignee"] else None,
        labels=issue["fields"]["labels"],
        components=[c['name'] for c in issue["fields"]["components"]],
        storypoints=int(issue["fields"]["customfield_10002"]) if issue["fields"]["customfield_10002"] else 0,
        sprints=[x['name'] for x in sprint_dict] if sprint_dict != None else None,
        updated_at=datetime.utcnow(),
        created=issue["fields"]["created"]
    )
    
    doc.save()

This of course only saves, but I've tried so many variants of update with upsert=True etc that I found, and none of them worked.

Do I really need to query each and every item before inserting?



from How do I upsert a document in MongoDB using mongoengine for Python?

No comments:

Post a Comment