How to use the pymongo.ReturnDocument function in pymongo

To help you get started, we’ve selected a few pymongo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Clinical-Genomics / scout / tests / adapter / mongo / test_case_handling.py View on Github external
def test_get_similar_cases_by_name_query(hpo_database, test_hpo_terms, case_obj):
    adapter = hpo_database

    # Make sure database contains HPO terms
    assert sum(1 for i in adapter.hpo_terms())

    # Give the case HPO terms
    case_obj["phenotype_terms"] = test_hpo_terms
    adapter.case_collection.find_one_and_update(
        {"_id": case_obj["_id"]},
        {"$set": {"phenotype_terms": test_hpo_terms}},
        return_document=pymongo.ReturnDocument.AFTER,
    )

    # Insert a case into the db
    adapter.case_collection.insert_one(case_obj)
    assert sum(1 for i in adapter.case_collection.find()) == 1

    # Add another case with slightly different phenotype:

    case_2 = copy.deepcopy(case_obj)
    case_2["_id"] = "case_2"
    case_2["phenotype_terms"] = test_hpo_terms[:-1]  # exclude last term

    # insert this case in database:
    adapter.case_collection.insert_one(case_2)
    assert sum(1 for i in adapter.case_collection.find()) == 2
github virtool / virtool / virtool / api / updates.py View on Github external
if document is None:
        document = {
            "_id": "software_update",
            "process": None,
            "releases": None
        }

        await db.status.insert_one(document)

    if not document.get("releases", None):
        document = await db.status.find_one_and_update({"_id": "software_update"}, {
            "$set": {
                "current_version": req.app["version"],
                "releases": await virtool.updates.get_releases(db, req.app["settings"], channel, req.app["version"])
            }
        }, return_document=pymongo.ReturnDocument)

        await dispatch("status", "update", virtool.utils.base_processor(document))

    releases = document.get("releases", list())

    try:
        latest_release = releases[0]
    except IndexError:
        return not_found("Could not find latest uninstalled release")

    document = await db.status.find_one_and_update({"_id": "software_update"}, {
        "$set": {
            "process": {
                "size": latest_release["size"],
                "step": "block_jobs",
                "progress": 0,
github hepsiburada / cikilop / src / repository / MigrationRepository.py View on Github external
def update_migration(self, mig_doc):
        updated = self._collection.find_one_and_replace({"_id": mig_doc["_id"]}, mig_doc,
                                                        return_document=ReturnDocument.AFTER)

        if updated:
            return Migration.load(updated)
        else:
            return None
github nebula-orchestrator / nebula / api-manager / functions / db_functions.py View on Github external
def mongo_update_app_containers_per(collection, app_name, containers_per):
    result = collection.find_one_and_update({'app_name': app_name},
                                            {'$set': {'containers_per': containers_per}},
                                            return_document=ReturnDocument.AFTER)
    return result
github hackingmaterials / atomate / atomate / utils / database.py View on Github external
def insert(self, d, update_duplicates=True):
        """
        Insert the task document ot the database collection.

        Args:
            d (dict): task document
            update_duplicates (bool): whether to update the duplicates
        """
        result = self.collection.find_one({"dir_name": d["dir_name"]}, ["dir_name", "task_id"])
        if result is None or update_duplicates:
            d["last_updated"] = datetime.datetime.utcnow()
            if result is None:
                if ("task_id" not in d) or (not d["task_id"]):
                    d["task_id"] = self.db.counter.find_one_and_update(
                        {"_id": "taskid"}, {"$inc": {"c": 1}},
                        return_document=ReturnDocument.AFTER)["c"]
                logger.info("Inserting {} with taskid = {}".format(d["dir_name"], d["task_id"]))
            elif update_duplicates:
                d["task_id"] = result["task_id"]
                logger.info("Updating {} with taskid = {}".format(d["dir_name"], d["task_id"]))
            d = jsanitize(d, allow_bson=True)
            self.collection.update_one({"dir_name": d["dir_name"]},
                                       {"$set": d}, upsert=True)
            return d["task_id"]
        else:
            logger.info("Skipping duplicate {}".format(d["dir_name"]))
            return None
github virtool / virtool / virtool / jobs / create_subtraction.py View on Github external
def set_stats(self):
        """
        Generate some stats for the FASTA file associated with this job. These numbers include nucleotide distribution,
        length distribution, and sequence count.

        """
        gc, count = virtool.subtractions.utils.calculate_fasta_gc(self.params["fasta_path"])

        self.db.subtraction.find_one_and_update({"_id": self.params["subtraction_id"]}, {
            "$set": {
                "gc": gc,
                "count": count
            }
        }, return_document=pymongo.ReturnDocument.AFTER, projection=virtool.subtractions.db.PROJECTION)

        self.dispatch("subtraction", "update", [self.params["subtraction_id"]])
github fourjr / statsy / cogs / clashroyale.py View on Github external
message = await channel.send('Clan Info')
                    await message.add_reaction(':refresh:477405504512065536')
            except (discord.Forbidden, discord.HTTPException):
                try:
                    await message.delete()
                except (NameError, discord.NotFound):
                    pass
                return await ctx.send(_('Statsy should have permissions to `Send Messages` and `Add Reactions` in #{}').format(channel.name))

            data = await self.bot.mongo.config.guilds.find_one_and_update({'guild_id': str(ctx.guild.id)}, {'$set': {
                'claninfo': {
                    'channel': str(channel.id),
                    'message': str(message.id),
                    'clans': clans
                }
            }}, upsert=True, return_document=ReturnDocument.AFTER)

            await self.clanupdate(data)
            await ctx.send(_('Configuration complete.'))
github Clinical-Genomics / scout / scout / adapter / mongo / case.py View on Github external
Args:
            case_obj(dict)

        Returns:
            updated_case(dict)
        """
        # Todo: Figure out and describe when this method destroys a case if invoked instead of
        # update_case
        LOG.info("Saving case %s", case_obj["_id"])
        # update updated_at of case to "today"

        case_obj["updated_at"] = datetime.datetime.now()

        updated_case = self.case_collection.find_one_and_replace(
            {"_id": case_obj["_id"]}, case_obj, return_document=pymongo.ReturnDocument.AFTER,
        )

        return updated_case
github numberly / mongo-thingy / mongo_thingy / __init__.py View on Github external
def find_one_and_replace(cls, *args, **kwargs):
        kwargs.setdefault("return_document", ReturnDocument.AFTER)
        result = cls.collection.find_one_and_replace(*args, **kwargs)
        if result is not None:
            return cls(result)
github virtool / virtool / virtool / api / account.py View on Github external
key_id = req.match_info.get("key_id")

    user_id = req["client"].user_id

    permissions = await virtool.db.utils.get_one_field(db.keys, "permissions", {"id": key_id, "user.id": user_id})

    if permissions is None:
        return not_found()

    permissions.update(data["permissions"])

    document = await db.keys.find_one_and_update({"id": key_id}, {
        "$set": {
            "permissions": permissions
        }
    }, return_document=ReturnDocument.AFTER, projection={"_id": False, "user": False})

    return json_response(document)