def insert(self, doc_or_docs,
               manipulate=True, safe=False, check_keys=True, **kwargs):
        """Insert a document(s) into this collection.

        If `manipulate` is set, the document(s) are manipulated using
        any :class:`~pymongo.son_manipulator.SONManipulator` instances
        that have been added to this
        :class:`~pymongo.database.Database`. Returns the ``"_id"`` of
        the inserted document or a list of ``"_id"`` values of the
        inserted documents.  If the document(s) does not already
        contain an ``"_id"`` one will be added.

        If `safe` is ``True`` then the insert will be checked for
        errors, raising :class:`~pymongo.errors.OperationFailure` if
        one occurred. Safe inserts wait for a response from the
        database, while normal inserts do not.

        Any additional keyword arguments imply ``safe=True``, and
        will be used as options for the resultant `getLastError`
        command. For example, to wait for replication to 3 nodes, pass
        ``w=3``.

        :Parameters:
          - `doc_or_docs`: a document or list of documents to be
            inserted
          - `manipulate` (optional): manipulate the documents before
            inserting?
          - `safe` (optional): check that the insert succeeded?
          - `check_keys` (optional): check if keys start with '$' or
            contain '.', raising :class:`~pymongo.errors.InvalidName`
            in either case
          - `**kwargs` (optional): any additional arguments imply
            ``safe=True``, and will be used as options for the
            `getLastError` command

        .. versionadded:: 1.8
           Support for passing `getLastError` options as keyword
           arguments.
        .. versionchanged:: 1.1
           Bulk insert works with any iterable

        .. mongodoc:: insert
        """
        docs = doc_or_docs
        return_one = False
        if isinstance(docs, dict):
            return_one = True
            docs = [docs]

        if manipulate:
            docs = [self.__database._fix_incoming(doc, self) for doc in docs]

        if kwargs:
            safe = True
        self.__database.connection._send_message(
            message.insert(self.__full_name, docs,
                           check_keys, safe, kwargs), safe)

        ids = [doc.get("_id", None) for doc in docs]
        return return_one and ids[0] or ids
Beispiel #2
0
    def insert(self, doc_or_docs,
               manipulate=True, safe=False, check_keys=True, **kwargs):
        """Insert a document(s) into this collection.

        If `manipulate` is set, the document(s) are manipulated using
        any :class:`~pymongo.son_manipulator.SONManipulator` instances
        that have been added to this
        :class:`~pymongo.database.Database`. Returns the ``"_id"`` of
        the inserted document or a list of ``"_id"`` values of the
        inserted documents.  If the document(s) does not already
        contain an ``"_id"`` one will be added.

        If `safe` is ``True`` then the insert will be checked for
        errors, raising :class:`~pymongo.errors.OperationFailure` if
        one occurred. Safe inserts wait for a response from the
        database, while normal inserts do not.

        Any additional keyword arguments imply ``safe=True``, and
        will be used as options for the resultant `getLastError`
        command. For example, to wait for replication to 3 nodes, pass
        ``w=3``.

        :Parameters:
          - `doc_or_docs`: a document or list of documents to be
            inserted
          - `manipulate` (optional): manipulate the documents before
            inserting?
          - `safe` (optional): check that the insert succeeded?
          - `check_keys` (optional): check if keys start with '$' or
            contain '.', raising :class:`~pymongo.errors.InvalidName`
            in either case
          - `**kwargs` (optional): any additional arguments imply
            ``safe=True``, and will be used as options for the
            `getLastError` command

        .. versionadded:: 1.8
           Support for passing `getLastError` options as keyword
           arguments.
        .. versionchanged:: 1.1
           Bulk insert works with any iterable

        .. mongodoc:: insert
        """
        docs = doc_or_docs
        return_one = False
        if isinstance(docs, dict):
            return_one = True
            docs = [docs]

        if manipulate:
            docs = [self.__database._fix_incoming(doc, self) for doc in docs]

        if kwargs:
            safe = True
        self.__database.connection._send_message(
            message.insert(self.__full_name, docs,
                           check_keys, safe, kwargs), safe)

        ids = [doc.get("_id", None) for doc in docs]
        return return_one and ids[0] or ids
    def insert(self, doc_or_docs,
               manipulate=True, safe=False, check_keys=True):
        """Insert a document(s) into this collection.

        If manipulate is set the document(s) are manipulated using any
        SONManipulators that have been added to this database. Returns the _id
        of the inserted document or a list of _ids of the inserted documents.
        If the document(s) does not already contain an '_id' one will be added.
        If `safe` is True then the insert will be checked for errors, raising
        OperationFailure if one occurred. Safe inserts wait for a response from
        the database, while normal inserts do not.

        :Parameters:
          - `doc_or_docs`: a SON object or list of SON objects to be inserted
          - `manipulate` (optional): manipulate the documents before inserting?
          - `safe` (optional): check that the insert succeeded?
          - `check_keys` (optional): check if keys start with '$' or
            contain '.', raising `pymongo.errors.InvalidName` in either case

        .. versionchanged:: 1.1
           Bulk insert works with any iterable
        """
        docs = doc_or_docs
        if isinstance(docs, dict):
            docs = [docs]

        if manipulate:
            docs = [self.__database._fix_incoming(doc, self) for doc in docs]

        self.__database.connection._send_message(
            message.insert(self.__full_name, docs, check_keys, safe), safe)

        ids = [doc.get("_id", None) for doc in docs]
        return len(ids) == 1 and ids[0] or ids
Beispiel #4
0
 def legacy_insert(self, operation, write_concern):
     """Do a legacy insert and return the result.
     """
     # We have to do this here since Collection.insert
     # throws away results and we need to check for jnote.
     client = self.collection.database.connection
     uuid_subtype = self.collection.uuid_subtype
     return client._send_message(
         insert(self.name, [operation], True, True,
             write_concern, False, uuid_subtype), True)
Beispiel #5
0
 def legacy_insert(self, operation, write_concern):
     """Do a legacy insert and return the result.
     """
     # We have to do this here since Collection.insert
     # throws away results and we need to check for jnote.
     client = self.collection.database.connection
     uuid_subtype = self.collection.uuid_subtype
     return client._send_message(
         insert(self.name, [operation], True, True, write_concern, False,
                uuid_subtype), True)
Beispiel #6
0
def test_pymongo():
    response = b"%s%s%s%s%s" % (struct.pack("<i", 4), struct.pack(
        "<q", 1), struct.pack("<i", 1), struct.pack(
            "<i", 1), bson.BSON.encode({"hello": "world"}))
    assert asynmongo._unpack_response(response, 1) == {
        'starting_from': 1,
        'number_returned': 1,
        'cursor_id': 1,
        'data': [{
            'hello': 'world'
        }]
    }

    payload = bson.BSON.encode({"hello": "world"})
    response = b"%s%s%s" % (struct.pack(
        "<B", 0), struct.pack("<i", len(payload)), payload)
    assert asynmongo._unpack_response(response, 2013) == {
        'first_payload_type': 0,
        'data': [{
            'hello': 'world'
        }],
        'first_payload_size': 22
    }

    opts = CodecOptions(SON)
    assert auth._auth_key(1, "a", "b") == "90b38d5dbfabd0b883e17ae67847220a"
    assert message.query(0, "%s.$cmd" % "mydb", 0, 1, SON({
        'getnonce': 1
    }), SON({}), opts) == (
        1804289383,
        b'>\x00\x00\x00gE\x8bk\x00\x00\x00\x00\xd4\x07\x00\x00\x00\x00\x00\x00mydb.$cmd\x00\x00\x00\x00\x00\x01\x00\x00\x00\x13\x00\x00\x00\x10getnonce\x00\x01\x00\x00\x00\x00\x05\x00\x00\x00\x00',
        19)
    assert message.query(0, "col.a", 0, 1, {"_id": 1}, None, opts) == (
        846930886,
        b'0\x00\x00\x00\xc6#{2\x00\x00\x00\x00\xd4\x07\x00\x00\x00\x00\x00\x00col.a\x00\x00\x00\x00\x00\x01\x00\x00\x00\x0e\x00\x00\x00\x10_id\x00\x01\x00\x00\x00\x00',
        14)
    assert message.update("col.a", 0, 0, {"_id": 1}, {
        "a": 1
    }, 1, (), False, opts) == (
        1681692777,
        b'8\x00\x00\x00i\x98<d\x00\x00\x00\x00\xd1\x07\x00\x00\x00\x00\x00\x00col.a\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x10_id\x00\x01\x00\x00\x00\x00\x0c\x00\x00\x00\x10a\x00\x01\x00\x00\x00\x00<\x00\x00\x00i\x98<d\x00\x00\x00\x00\xd4\x07\x00\x00\x00\x00\x00\x00col.$cmd\x00\x00\x00\x00\x00\xff\xff\xff\xff\x17\x00\x00\x00\x10getlasterror\x00\x01\x00\x00\x00\x00',
        14)

    msg = message.delete("col.a", {"_id": 1}, 1, (), opts, 0)
    assert len(msg) == 3 and msg[0] == 1714636915 and msg[-1] == 14

    msg = message.insert("col.a", [{"a": 1}], False, 1, (), 0, opts)
    assert len(msg) == 3 and msg[0] == 1957747793 and msg[-1] == 12
Beispiel #7
0
    def insert(self,
               doc_or_docs,
               manipulate=True,
               safe=False,
               check_keys=True):
        """Insert a document(s) into this collection.

        If manipulate is set the document(s) are manipulated using any
        SONManipulators that have been added to this database. Returns the _id
        of the inserted document or a list of _ids of the inserted documents.
        If the document(s) does not already contain an '_id' one will be added.
        If `safe` is True then the insert will be checked for errors, raising
        OperationFailure if one occurred. Safe inserts wait for a response from
        the database, while normal inserts do not.

        :Parameters:
          - `doc_or_docs`: a SON object or list of SON objects to be inserted
          - `manipulate` (optional): manipulate the documents before inserting?
          - `safe` (optional): check that the insert succeeded?
          - `check_keys` (optional): check if keys start with '$' or
            contain '.', raising `pymongo.errors.InvalidName` in either case

        .. versionchanged:: 1.1
           Bulk insert works with any iterable

        .. mongodoc:: insert
        """
        docs = doc_or_docs
        return_one = False
        if isinstance(docs, dict):
            return_one = True
            docs = [docs]

        if manipulate:
            docs = [self.__database._fix_incoming(doc, self) for doc in docs]

        self.__database.connection._send_message(
            message.insert(self.__full_name, docs, check_keys, safe), safe)

        ids = [doc.get("_id", None) for doc in docs]
        return return_one and ids[0] or ids
Beispiel #8
0
    def insert(self, doc_or_docs, manipulate=True, safe=False, check_keys=True, continue_on_error=False, **kwargs):
        """Insert a document(s) into this collection.

        If `manipulate` is ``True``, the document(s) are manipulated using
        any :class:`~pymongo.son_manipulator.SONManipulator` instances
        that have been added to this :class:`~pymongo.database.Database`.
        In this case an ``"_id"`` will be added if the document(s) does
        not already contain one and the ``"id"`` (or list of ``"_id"``
        values for more than one document) will be returned.
        If `manipulate` is ``False`` and the document(s) does not include
        an ``"_id"`` one will be added by the server. The server
        does not return the ``"_id"`` it created so ``None`` is returned.

        If `safe` is ``True`` then the insert will be checked for
        errors, raising :class:`~pymongo.errors.OperationFailure` if
        one occurred. Safe inserts wait for a response from the
        database, while normal inserts do not.

        Any additional keyword arguments imply ``safe=True``, and
        will be used as options for the resultant `getLastError`
        command. For example, to wait for replication to 3 nodes, pass
        ``w=3``.

        :Parameters:
          - `doc_or_docs`: a document or list of documents to be
            inserted
          - `manipulate` (optional): manipulate the documents before
            inserting?
          - `safe` (optional): check that the insert succeeded?
          - `check_keys` (optional): check if keys start with '$' or
            contain '.', raising :class:`~pymongo.errors.InvalidName`
            in either case
          - `continue_on_error` (optional): If True, the database will not stop
            processing a bulk insert if one fails (e.g. due to duplicate IDs).
            This makes bulk insert behave similarly to a series of single
            inserts, except lastError will be set if any insert fails, not just
            the last one. If multiple errors occur, only the most recent will
            be reported by :meth:`~pymongo.database.Database.error`.
          - `**kwargs` (optional): any additional arguments imply
            ``safe=True``, and will be used as options for the
            `getLastError` command

        .. note:: `continue_on_error` requires server version **>= 1.9.1**

        .. versionadded:: 2.0.1+
           Support for continue_on_error.
        .. versionadded:: 1.8
           Support for passing `getLastError` options as keyword
           arguments.
        .. versionchanged:: 1.1
           Bulk insert works with any iterable

        .. mongodoc:: insert
        """
        docs = doc_or_docs
        return_one = False
        if isinstance(docs, dict):
            return_one = True
            docs = [docs]

        if manipulate:
            docs = [self.__database._fix_incoming(doc, self) for doc in docs]

        if self.safe or kwargs:
            safe = True
            if not kwargs:
                kwargs.update(self.get_lasterror_options())

        self.__database.connection._send_message(
            message.insert(self.__full_name, docs, check_keys, safe, continue_on_error, kwargs), safe
        )

        ids = [doc.get("_id", None) for doc in docs]
        return return_one and ids[0] or ids
Beispiel #9
0
    def insert(self,
               doc_or_docs,
               manipulate=True,
               safe=False,
               check_keys=True,
               continue_on_error=False,
               **kwargs):
        """Insert a document(s) into this collection.

        If `manipulate` is ``True``, the document(s) are manipulated using
        any :class:`~pymongo.son_manipulator.SONManipulator` instances
        that have been added to this :class:`~pymongo.database.Database`.
        In this case an ``"_id"`` will be added if the document(s) does
        not already contain one and the ``"id"`` (or list of ``"_id"``
        values for more than one document) will be returned.
        If `manipulate` is ``False`` and the document(s) does not include
        an ``"_id"`` one will be added by the server. The server
        does not return the ``"_id"`` it created so ``None`` is returned.

        If `safe` is ``True`` then the insert will be checked for
        errors, raising :class:`~pymongo.errors.OperationFailure` if
        one occurred. Safe inserts wait for a response from the
        database, while normal inserts do not.

        Any additional keyword arguments imply ``safe=True``, and
        will be used as options for the resultant `getLastError`
        command. For example, to wait for replication to 3 nodes, pass
        ``w=3``.

        :Parameters:
          - `doc_or_docs`: a document or list of documents to be
            inserted
          - `manipulate` (optional): manipulate the documents before
            inserting?
          - `safe` (optional): check that the insert succeeded?
          - `check_keys` (optional): check if keys start with '$' or
            contain '.', raising :class:`~pymongo.errors.InvalidName`
            in either case
          - `continue_on_error` (optional): If True, the database will not stop
            processing a bulk insert if one fails (e.g. due to duplicate IDs).
            This makes bulk insert behave similarly to a series of single
            inserts, except lastError will be set if any insert fails, not just
            the last one. If multiple errors occur, only the most recent will
            be reported by :meth:`~pymongo.database.Database.error`.
          - `**kwargs` (optional): any additional arguments imply
            ``safe=True``, and will be used as options for the
            `getLastError` command

        .. note:: `continue_on_error` requires server version **>= 1.9.1**

        .. versionadded:: 2.1
           Support for continue_on_error.
        .. versionadded:: 1.8
           Support for passing `getLastError` options as keyword
           arguments.
        .. versionchanged:: 1.1
           Bulk insert works with any iterable

        .. mongodoc:: insert
        """
        docs = doc_or_docs
        return_one = False
        if isinstance(docs, dict):
            return_one = True
            docs = [docs]

        if manipulate:
            docs = [self.__database._fix_incoming(doc, self) for doc in docs]

        if self.safe or kwargs:
            safe = True
            if not kwargs:
                kwargs.update(self.get_lasterror_options())

        self.__database.connection._send_message(
            message.insert(self.__full_name, docs, check_keys, safe, kwargs,
                           continue_on_error, self.__uuid_subtype), safe)

        ids = [doc.get("_id", None) for doc in docs]
        return return_one and ids[0] or ids