当前位置: 首页>>代码示例>>Python>>正文


Python pymongo.collection方法代码示例

本文整理汇总了Python中pymongo.collection方法的典型用法代码示例。如果您正苦于以下问题:Python pymongo.collection方法的具体用法?Python pymongo.collection怎么用?Python pymongo.collection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pymongo的用法示例。


在下文中一共展示了pymongo.collection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: xtract

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def xtract(clazz_or_instance):
    """
    Extract class name from class, removing the Service/Controller/Resource ending and adding a plural -s or -ies.
    :param clazz_or_instance: the class object
    :return: the name of the desired collection
    """
    clazz_name = clazz_or_instance.__name__ if inspect.isclass(
        clazz_or_instance) else clazz_or_instance.__class__.__name__
    name = re.split('Service|Controller|Resource', clazz_name)[0]
    if name[-2:] in ['sh', 'ch'] or name[-1:] in ['s', 'x', 'z']:
        name = f'{name}es'
    elif name[-1:] == 'y' and (name[-2:-1] in ["a", "e", "i", "o", "u"] or name[-3:-2] == 'qu'):
        name = f'{name[-1:]}ies'
    else:
        name = f'{name}s'
    return name 
开发者ID:accelero-cloud,项目名称:appkernel,代码行数:18,代码来源:repository.py

示例2: create_index

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def create_index(collection, field_name, sort_order, unique=False):
        # type: (pymongo.collection.Collection, str, SortOrder, bool) -> ()
        """
        Args:
            collection(pymongo.collection.Collection): the collection to which the index is applied to
            field_name(str): the name of the document field which is being indexed
            sort_order(SortOrder): the sort order
            unique(bool): if true (false by default) it will create a unique index
        """
        if field_name not in collection.index_information():
            if isinstance(sort_order, SortOrder):
                direction = pymongo.ASCENDING if sort_order == SortOrder.ASC else pymongo.DESCENDING
            else:
                direction = sort_order
            collection.create_index(
                [(field_name, direction)],
                unique=unique, background=True, name='{}_idx'.format(field_name)) 
开发者ID:accelero-cloud,项目名称:appkernel,代码行数:19,代码来源:repository.py

示例3: load_mongo_col

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def load_mongo_col(col: Collection) -> dict:
    """Load the pymongo collection to a dictionary.

    In the dictionary. The key will be the '_id' and in each value which is a dictionary there will also be a
    key '_id' so that the structure will be the same as the filesystem collection.

    Parameters
    ----------
    col : Collection
        The mongodb collection.

    Returns
    -------
    dct : dict
        A dictionary with all the info in the collection.
    """
    return {
        doc['_id']: doc for doc in col.find({})
    } 
开发者ID:regro,项目名称:regolith,代码行数:21,代码来源:mongoclient.py

示例4: load_database

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def load_database(self, db: dict):
        """Load the database information from mongo database.

        It populate the 'dbs' attribute with a dictionary like {database: {collection: docs_dict}}.

        Parameters
        ----------
        db : dict
            The dictionary of data base information, such as 'name'.
        """
        dbs: dict = self.dbs
        client: pymongo.MongoClient = self.client
        mongodb = client[db['name']]
        for colname in mongodb.list_collection_names():
            col = mongodb[colname]
            dbs[db['name']][colname] = load_mongo_col(col)
        return 
开发者ID:regro,项目名称:regolith,代码行数:19,代码来源:mongoclient.py

示例5: dump_database

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def dump_database(self, db):
        """Dumps a database dict via mongoexport."""
        dbpath = dbpathname(db, self.rc)
        os.makedirs(dbpath, exist_ok=True)
        to_add = []
        colls = self.client[db["name"]].collection_names(
            include_system_collections=False
        )
        for collection in colls:
            f = os.path.join(dbpath, collection + ".json")
            cmd = [
                "mongoexport",
                "--db",
                db["name"],
                "--collection",
                collection,
                "--out",
                f,
            ]
            subprocess.check_call(cmd)
            to_add.append(os.path.join(db["path"], collection + ".json"))
        return to_add 
开发者ID:regro,项目名称:regolith,代码行数:24,代码来源:mongoclient.py

示例6: __init__

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def __init__(
        self,
        collection: Union[
            pymongo.collection.Collection, mongomock.collection.Collection
        ],
        resource_cls: EntryResource,
        resource_mapper: BaseResourceMapper,
    ):
        super().__init__(collection, resource_cls, resource_mapper)
        self.transformer = MongoTransformer(mapper=resource_mapper)

        self.provider_prefix = CONFIG.provider.prefix
        self.provider_fields = CONFIG.provider_fields.get(resource_mapper.ENDPOINT, [])
        self.parser = LarkParser(
            version=(0, 10, 1), variant="default"
        )  # The MongoTransformer only supports v0.10.1 as the latest grammar

        # check aliases do not clash with mongo operators
        self._check_aliases(self.resource_mapper.all_aliases())
        self._check_aliases(self.resource_mapper.all_length_aliases()) 
开发者ID:Materials-Consortia,项目名称:optimade-python-tools,代码行数:22,代码来源:mongo.py

示例7: test_trace_plugin__auto_db__pymongo

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def test_trace_plugin__auto_db__pymongo(
    mock_send_report, handler_with_trace_auto_db_pymongo, mock_context, monkeypatch
):
    monkeypatch.setattr(
        pymongo.collection, "Collection", mongomock.collection.Collection
    )
    monkeypatch.setattr(pymongo, "MongoClient", mongomock.MongoClient)
    setattr(mongomock.database.Database, "address", ("localhost", 27017))

    iopipe, handler = handler_with_trace_auto_db_pymongo

    assert len(iopipe.config["plugins"]) == 1

    handler({}, mock_context)

    assert len(iopipe.report.performance_entries) == 0

    db_traces = iopipe.report.db_trace_entries

    assert len(db_traces) == 3

    for db_trace in db_traces:
        assert db_trace["dbType"] == "mongodb"
        assert db_trace["request"]["hostname"] == "localhost"
        assert db_trace["request"]["port"] == 27017
        assert db_trace["request"]["db"] == "test"
        assert db_trace["request"]["table"] == "my_collection"

    assert db_traces[0]["request"]["command"] == "insert_one"
    assert db_traces[2]["request"]["command"] == "update" 
开发者ID:iopipe,项目名称:iopipe-python,代码行数:32,代码来源:test_plugin.py

示例8: __init__

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def __init__(self, connection_object: pymongo.collection.Collection, user_class, *expressions):
        super().__init__(*expressions)
        self.connection: pymongo.collection.Collection = connection_object
        self.user_class = user_class 
开发者ID:accelero-cloud,项目名称:appkernel,代码行数:6,代码来源:repository.py

示例9: create_text_index

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def create_text_index(collection, field_name, *args):
        # type: (pymongo.collection.Collection, str, SortOrder, bool) -> ()
        MongoRepository.create_index(collection, field_name, pymongo.TEXT) 
开发者ID:accelero-cloud,项目名称:appkernel,代码行数:5,代码来源:repository.py

示例10: create_unique_index

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def create_unique_index(collection, field_name, sort_order):
        MongoRepository.create_index(collection, field_name, sort_order, unique=True) 
开发者ID:accelero-cloud,项目名称:appkernel,代码行数:4,代码来源:repository.py

示例11: delete_all

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def delete_all(cls):
        """
        deletes all documents from the collection
        :return: the count of deleted documents
        """
        return cls.get_collection().delete_many({}).deleted_count 
开发者ID:accelero-cloud,项目名称:appkernel,代码行数:8,代码来源:repository.py

示例12: import_jsons

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def import_jsons(dbpath: str, dbname: str, host: str = None, uri: str = None) -> None:
    """Import the json files to mongo db.

    Each json file will be a collection in the database. The _id will be the same as it is in the json file.

    Parameters
    ----------
    dbpath : str
        The path to the db folder.

    dbname : str
        The name of the database in mongo.

    host : str
        The hostname or IP address or Unix domain socket path of a single mongod or mongos instance to connect
        to, or a mongodb URI, or a list of hostnames / mongodb URIs.

    uri : str
        Specify a resolvable URI connection string (enclose in quotes) to connect to the MongoDB deployment.
    """
    for json_path in Path(dbpath).glob("*.json"):
        cmd = ["mongoimport"]
        if host is not None:
            cmd += ['--host', host, "--db", dbname]
        if uri is not None:
            cmd += ['--uri', uri]
        cmd += ["--collection", json_path.stem, "--file", str(json_path)]
        subprocess.check_call(cmd)
    return 
开发者ID:regro,项目名称:regolith,代码行数:31,代码来源:mongoclient.py

示例13: import_yamls

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def import_yamls(dbpath: str, dbname: str, host: str = None, uri: str = None) -> None:
    """Import the yaml files to mongo db.

    Each yaml file will be a collection in the database. The _id will be the id_key for each doc in the yaml file.

    Parameters
    ----------
    dbpath : str
        The path to the db folder.

    dbname : str
        The name of the database in mongo.

    host : str
        The hostname or IP address or Unix domain socket path of a single mongod or mongos instance to connect
        to, or a mongodb URI, or a list of hostnames / mongodb URIs.

    uri : str
        Specify a resolvable URI connection string (enclose in quotes) to connect to the MongoDB deployment.
    """
    yaml_files = itertools.chain(Path(dbpath).glob('*.yaml'), Path(dbpath).glob('*.yml'))
    with TemporaryDirectory() as tempd:
        for yaml_file in yaml_files:
            json_file = Path(tempd).joinpath(yaml_file.with_suffix('.json').name)
            loader = YAML(typ='safe')
            loader.constructor.yaml_constructors[u'tag:yaml.org,2002:timestamp'] = \
                loader.constructor.yaml_constructors[u'tag:yaml.org,2002:str']
            fsclient.yaml_to_json(str(yaml_file), str(json_file), loader=loader)
        import_jsons(tempd, dbname, host=host, uri=uri)
    return 
开发者ID:regro,项目名称:regolith,代码行数:32,代码来源:mongoclient.py

示例14: all_documents

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def all_documents(self, collname, copy=True):
        """Returns an iterable over all documents in a collection."""
        if copy:
            return deepcopy(self.chained_db.get(collname, {})).values()
        return self.chained_db.get(collname, {}).values() 
开发者ID:regro,项目名称:regolith,代码行数:7,代码来源:mongoclient.py

示例15: insert_one

# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import collection [as 别名]
def insert_one(self, dbname, collname, doc):
        """Inserts one document to a database/collection."""
        coll = self.client[dbname][collname]
        if ON_PYMONGO_V2:
            i = coll.insert(doc)
            return InsertOneProxy(i, True)
        else:
            return coll.insert_one(doc) 
开发者ID:regro,项目名称:regolith,代码行数:10,代码来源:mongoclient.py


注:本文中的pymongo.collection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。