convert selector used in an upsert statement into a document
503715
Document convertSelectorToDocument(Document selector) {
        Document document = new Document();
        for (String key : selector.keySet()) {
            if (key.startsWith("$")) {
                continue;
            }

            Object value = selector.get(key);
            if (!Utils.containsQueryExpression(value)) {
                Utils.changeSubdocumentValue(document, key, value, (AtomicReference<Integer>) null);
            }
        }
        return document;
    }
1220325
function normalizeSelector(selector) {
  var parts = selector.match(/[^\s>]+|>/ig);
  selector = (parts) ? parts.join(' ') : '';
  return {
    normalized: selector,
    parts: parts || []
  };
}
1131409
def apply_selector(objs, selector):
    ''''''
    out = []
    for obj in objs:
        timer.log('Applying selector: %s' % selector)
        out += list(jsonselect.match(selector, objs))
        timer.log('done applying selector')
    return out
925256
function _wrapSelectedStatements (wrapperName, err) {
        var editor = EditorManager.getActiveEditor();
        if (!editor) {
            return;
        }
        initializeRefactoringSession(editor);

        var startIndex = current.startIndex,
            endIndex = current.endIndex,
            selectedText = current.selectedText,
            pos;

        if (selectedText.length === 0) {
            var statementNode = RefactoringUtils.findSurroundASTNode(current.ast, {start: startIndex}, ["Statement"]);
            if (!statementNode) {
                current.editor.displayErrorMessageAtCursor(err);
                return;
            }
            selectedText = current.text.substr(statementNode.start, statementNode.end - statementNode.start);
            startIndex = statementNode.start;
            endIndex = statementNode.end;
        } else {
            var selectionDetails = RefactoringUtils.normalizeText(selectedText, startIndex, endIndex);
            selectedText = selectionDetails.text;
            startIndex = selectionDetails.start;
            endIndex = selectionDetails.end;
        }

        if (!RefactoringUtils.checkStatement(current.ast, startIndex, endIndex, selectedText)) {
            current.editor.displayErrorMessageAtCursor(err);
            return;
        }

        pos = {
            "start": current.cm.posFromIndex(startIndex),
            "end": current.cm.posFromIndex(endIndex)
        };

        current.document.batchOperation(function() {
            current.replaceTextFromTemplate(wrapperName, {body: selectedText}, pos);
        });

        if (wrapperName === TRY_CATCH) {
            var cursorLine = current.editor.getSelection().end.line - 1,
                startCursorCh = current.document.getLine(cursorLine).indexOf("\/\/"),
                endCursorCh = current.document.getLine(cursorLine).length;

            current.editor.setSelection({"line": cursorLine, "ch": startCursorCh}, {"line": cursorLine, "ch": endCursorCh});
        } else if (wrapperName === WRAP_IN_CONDITION) {
            current.editor.setSelection({"line": pos.start.line, "ch": pos.start.ch + 4}, {"line": pos.start.line, "ch": pos.start.ch + 13});
        }
    }
277988
function parseChunks(selector, selectors) {
          var parts = [], extra, matches, i;

          do {
            chunker.exec("");
            matches = chunker.exec(selector);

            if (matches) {
              selector = matches[3];
              parts.push(matches[1]);

              if (matches[2]) {
                extra = matches[3];
                break;
              }
            }
          } while (matches);

          if (extra) {
            parseChunks(extra, selectors);
          }

          selector = [];
          for (i = 0; i < parts.length; i++) {
            if (parts[i] != '>') {
              selector.push(compile(parts[i], [], parts[i - 1] === '>'));
            }
          }

          selectors.push(selector);

          return selectors;
        }
49852
function() {
                var selectors = [], s, rules;
                save();

                s = $(this.selector);
                while (s) {
                    selectors.push(s);
                    while ($(this.comment)) {
                        // do nothing
                    }
                    if (! $(',')) { break; }
                    while ($(this.comment)) {
                        // do nothing
                    }
                    s = $(this.selector);
                }
                if (s) {
                    while ($(this.comment)) {
                        // do nothing
                    }
                }

                if (selectors.length > 0 && (rules = $(this.block))) {
                    if (selectors.length === 1 &&
                        selectors[0].elements.length &&
                        selectors[0].elements[0].value === 'Map') {
                        var rs = new tree.Ruleset(selectors, rules);
                        rs.isMap = true;
                        return rs;
                    }
                    return new tree.Ruleset(selectors, rules);
                } else {
                    // Backtrack
                    restore();
                }
            }
427054
function (selector) {
    var self = this;
    // you can pass a literal function instead of a selector
    if (_.isFunction(selector)) {
      self._isSimple = false;
      self._selector = selector;
      self._recordPathUsed('');
      return function (doc) {
        return {result: !!selector.call(doc)};
      };
    }

    // shorthand -- scalars match _id
    if (LocalCollection._selectorIsId(selector)) {
      self._selector = {_id: selector};
      self._recordPathUsed('_id');
      return function (doc) {
        return {result: EJSON.equals(doc._id, selector)};
      };
    }

    // protect against dangerous selectors.  falsey and {_id: falsey} are both
    // likely programmer error, and not what you want, particularly for
    // destructive operations.
    if (!selector || (('_id' in selector) && !selector._id)) {
      self._isSimple = false;
      return nothingMatcher;
    }

    // Top level can't be an array or true or binary.
    if (typeof(selector) === 'boolean' || isArray(selector) ||
        EJSON.isBinary(selector))
      throw new Error("Invalid selector: " + selector);

    self._selector = EJSON.clone(selector);
    return compileDocumentSelector(selector, self, {isRoot: true});
  }
604114
function sqliteBulkUpsert(model, data) {
  var queries = ["BEGIN"];
  var values = [];

  // Transform data
  _.each(data, function(d) {
    var query = "INSERT OR REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
    query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));

    // Put in ?'s
    query = query.replace("[[VALUES]]", _.map(d, function(v) {
      return "?";
    }).join(", "));

    // Get values
    values = values.concat(_.values(d));
    queries.push(query);
  });

  // Create final output and format
  queries.push("COMMIT");
  return {
    query: queries.join("; "),
    replacements: values
  };
}
218211
function( selector ) {
    return (
    this
    .filter( selector || null )
    .avoid( 'h-jinze' )
    .replace(
      TYPESET.jinze.touwei,
      function( portion, match ) {
        var elem = $.create( 'h-jinze', 'touwei' )
        elem.innerHTML = match[0]
        return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 ) ? elem : ''
      }
    )
    .replace(
      TYPESET.jinze.wei,
      function( portion, match ) {
        var elem = $.create( 'h-jinze', 'wei' )
        elem.innerHTML = match[0]
        return portion.index === 0 ? elem : ''
      }
    )
    .replace(
      TYPESET.jinze.tou,
      function( portion, match ) {
        var elem = $.create( 'h-jinze', 'tou' )
        elem.innerHTML = match[0]
        return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 )
          ? elem : ''
      }
    )
    .replace(
      TYPESET.jinze.middle,
      function( portion, match ) {
        var elem = $.create( 'h-jinze', 'middle' )
        elem.innerHTML = match[0]
        return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 )
          ? elem : ''
      }
    )
    .endAvoid()
    .endFilter()
    )
  }
1178211
function matchesSelector(doc, selector) {
  /* istanbul ignore if */
  if (typeof selector !== 'object') {
    // match the CouchDB error message
    throw 'Selector error: expected a JSON object';
  }

  selector = massageSelector(selector);
  var row = {
    'doc': doc
  };

  var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
  return rowsMatched && rowsMatched.length === 1;
}
306134
private function executeUpsert($document, array $options)
    {
        $options['upsert'] = true;
        $criteria = $this->getQueryForDocument($document);

        $data = $this->pb->prepareUpsertData($document);

        // Set the initial version for each upsert
        if ($this->class->isVersioned) {
            $versionMapping = $this->class->fieldMappings[$this->class->versionField];
            if ($versionMapping['type'] === 'int') {
                $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document));
                $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion);
            } elseif ($versionMapping['type'] === 'date') {
                $nextVersionDateTime = new \DateTime();
                $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp());
                $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime);
            }
            $data['$set'][$versionMapping['name']] = $nextVersion;
        }

        foreach (array_keys($criteria) as $field) {
            unset($data['$set'][$field]);
        }

        // Do not send an empty $set modifier
        if (empty($data['$set'])) {
            unset($data['$set']);
        }

        /* If there are no modifiers remaining, we're upserting a document with
         * an identifier as its only field. Since a document with the identifier
         * may already exist, the desired behavior is "insert if not exists" and
         * NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set
         * the identifier to the same value in our criteria.
         *
         * This will fail for versions before MongoDB 2.6, which require an
         * empty $set modifier. The best we can do (without attempting to check
         * server versions in advance) is attempt the 2.6+ behavior and retry
         * after the relevant exception.
         *
         * See: https://jira.mongodb.org/browse/SERVER-12266
         */
        if (empty($data)) {
            $retry = true;
            $data = array('$set' => array('_id' => $criteria['_id']));
        }

        try {
            $this->collection->update($criteria, $data, $options);
            return;
        } catch (\MongoCursorException $e) {
            if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) {
                throw $e;
            }
        }

        $this->collection->update($criteria, array('$set' => new \stdClass), $options);
    }
1206408
public function upsert($document, $parentPath = null)
    {
        $class     = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);

        if (!$class->isEmbeddedDocument) {
            $qb         = $this->dm->createQueryBuilder($class->name);
            $identifier = $class->createIdentifier($document);

            $qb->update();
            $qb->setIdentifier($identifier);
        } elseif ($parentPath === null) {
            throw new \InvalidArgumentException;
        }

        foreach ($changeset as $attributeName => $change) {
            if ($class->isIdentifier($attributeName)) {
                continue;
            }

            list($old, $new) = $change;

            $mapping            = $class->getPropertyMetadata($attributeName);
            $discriminatorValue = null;

            if ($mapping->embedded && $mapping->isOne()) {
                $embeddedClassName  = get_class($new);
                $embeddedClass      = $this->dm->getClassMetadata($embeddedClassName);
                $discriminatorValue = $embeddedClass->getEmbeddedDiscriminatorValue($mapping, $new);
                //@Many will set discriminator in updatePath
            }

            if ($class->isEmbeddedDocument) {
                $path = $parentPath->map($attributeName, $discriminatorValue);
            } else {
                $path = $qb->attr($attributeName, $discriminatorValue);
            }

            $this->updatePath($path, $old, $new, true);
        }

        // add discriminator if the class has one
        if ($class->discriminatorAttribute !== null) {
            if ($class->isEmbeddedDocument) {
                $path = $parentPath->map($class->discriminatorAttribute);
            } else {
                $path = $qb->attr($class->discriminatorAttribute);
            }

            $path->set(
                $class->discriminatorValue !== null
                    ? $class->discriminatorValue
                    : $class->name
            );
        }

        if ($this->class->isVersioned) {
            // Set the initial version. Only supported on top-level documents.

            $versionMapping = $this->class->getPropertyMetadata($this->class->versionAttribute);
            $nextVersion    = null;

            if ($versionMapping->type === Type::INT) {
                $nextVersion = max(1, (int)$versionMapping->getValue($document));
            } elseif ($versionMapping->isDateType()) {
                $nextVersion = new \DateTime();
            }

            $nextVersion = $versionMapping->getType()->convertToDatabaseValue($nextVersion);
            $versionMapping->setValue($document, $nextVersion);

            $qb->attr($versionMapping->name)->set($nextVersion);
        }

        //DynamoDB will upsert even if we only pass the id conditional with no UpdateExpression

        if (!$class->isEmbeddedDocument) {
            $qb->getQuery()->execute();
        }
    }
650035
function validateAndGetQuerySelector (selector) {
  try {
    var el = document.querySelector(selector);
    if (!el) {
      warn('No element was found matching the selector: "%s"', selector);
    }
    return el;
  } catch (e) {  // Capture exception if it's not a valid selector.
    warn('"%s" is not a valid selector', selector);
    return undefined;
  }
}
1135452
def _insert(collection_name, docs, check_keys, flags, opts):
    """"""
    encode = _dict_to_bson  # Make local. Uses extensions.
    if len(docs) == 1:
        encoded = encode(docs[0], check_keys, opts)
        return b"".join([
            b"\x00\x00\x00\x00",  # Flags don't matter for one doc.
            _make_c_string(collection_name),
            encoded]), len(encoded)

    encoded = [encode(doc, check_keys, opts) for doc in docs]
    if not encoded:
        raise InvalidOperation("cannot do an empty bulk insert")
    return b"".join([
        _pack_int(flags),
        _make_c_string(collection_name),
        b"".join(encoded)]), max(map(len, encoded))
44222
function upsertDocumentController(req, res) {
                    var modelName = req.params.modelName,
                        id = req.params.documentId,
                        user = req.admin_user,
                        data = _.extend({}, req.body, req.files),
                        modelConfig = registry.models[modelName],
                        form;

                    polymorphGetDocument(modelConfig.model, modelConfig.is_single, id).then(
                        function createTheForm(document) {
                            var action = document ? 'update' : 'create';
                            var docType = document && document._doc.__t;
                            if (docType) modelConfig = registry.models[docType];
                            var FormType = modelConfig.options.form;
                            if (!user.hasPermissions(modelConfig.modelName, action)) throw new Error('unauthorized');
                            form = new FormType(modelConfig.options, modelConfig.model, document, data);
                            return form.save();
                        }
                    ).then(
                        function (document) {
                            modelConfig.options.post(document);
                            return form;
                        },
                        function (err) {
                            err.modelConfig = modelConfig;
                            err.form = form;
                            if (!form) throw err;

                            form.errors = form.errors || {};
                            if (err.name == 'ValidationError') {
                                form.errors = _.merge(form.errors, err.errors);
                            } else if (err.name === 'MongoError' && err.code == 11000) {
                                form.errors.exception = err;
                                err.name = "Duplicate";
                                var msg = '{' + err.err.split('$').pop().split('{').pop();
                                var ObjectID = /ObjectId\(\'(\w+)\'\)/.exec(msg);
                                err.fields = '\n<br />';
                                err.fields += (ObjectID.length == 2) ? '<a href="' + ObjectID[1] + '" target="_blank">Click to open duplicate document</a>' :
                                    msg;
                            } else {
                                form.errors.exception = err;
                            }
                            if (_.isEmpty(form.errors)) return form;
                            throw err;
                        }
                    ).then(
                        function (form) {
                            res._debug_form = form;
                            var response = form.instance.toJSON();
                            response.id = response.id || form.instance._id;
                            response.label = response.label || form.instance.name || form.instance.title || form.instance.toString();
                            return response;
                        }
                    ).then(
                        function (response) {
                            res.json(200, response);
                        },
                        function (err) {
                            err.form = res._debug_form;
                            res.json(422, err);
                        }
                    ).end();
                }
975924
def _update(self, sock_info, criteria, document, upsert=False,
                check_keys=True, multi=False, manipulate=False,
                write_concern=None, op_id=None, ordered=True,
                bypass_doc_val=False, collation=None, array_filters=None,
                session=None, retryable_write=False):
        """"""
        common.validate_boolean("upsert", upsert)
        if manipulate:
            document = self.__database._fix_incoming(document, self)
        collation = validate_collation_or_none(collation)
        write_concern = write_concern or self.write_concern
        acknowledged = write_concern.acknowledged
        update_doc = SON([('q', criteria),
                          ('u', document),
                          ('multi', multi),
                          ('upsert', upsert)])
        if collation is not None:
            if sock_info.max_wire_version < 5:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.4+ to use collations.')
            elif not acknowledged:
                raise ConfigurationError(
                    'Collation is unsupported for unacknowledged writes.')
            else:
                update_doc['collation'] = collation
        if array_filters is not None:
            if sock_info.max_wire_version < 6:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.6+ to use array_filters.')
            elif not acknowledged:
                raise ConfigurationError(
                    'arrayFilters is unsupported for unacknowledged writes.')
            else:
                update_doc['arrayFilters'] = array_filters
        command = SON([('update', self.name),
                       ('ordered', ordered),
                       ('updates', [update_doc])])
        if not write_concern.is_server_default:
            command['writeConcern'] = write_concern.document

        if not sock_info.op_msg_enabled and not acknowledged:
            # Legacy OP_UPDATE.
            return self._legacy_write(
                sock_info, 'update', command, op_id,
                bypass_doc_val, message.update, self.__full_name, upsert,
                multi, criteria, document, False, write_concern.document,
                check_keys, self.__write_response_codec_options)

        # Update command.
        if bypass_doc_val and sock_info.max_wire_version >= 4:
            command['bypassDocumentValidation'] = True

        # The command result has to be published for APM unmodified
        # so we make a shallow copy here before adding updatedExisting.
        result = sock_info.command(
            self.__database.name,
            command,
            write_concern=write_concern,
            codec_options=self.__write_response_codec_options,
            session=session,
            client=self.__database.client,
            retryable_write=retryable_write).copy()
        _check_write_command_response(result)
        # Add the updatedExisting field for compatibility.
        if result.get('n') and 'upserted' not in result:
            result['updatedExisting'] = True
        else:
            result['updatedExisting'] = False
            # MongoDB >= 2.6.0 returns the upsert _id in an array
            # element. Break it out for backward compatibility.
            if 'upserted' in result:
                result['upserted'] = result['upserted'][0]['_id']

        if not acknowledged:
            return None
        return result
555954
protected DocumentType upsertType(
            String reference,
            String name,
            ExecutionContext executionContext) {

        DocumentType documentType = documentTypeRepository.findByReference(reference);
        if(documentType != null) {
            documentType.setName(name);
        } else {
            documentType = documentTypeRepository.create(reference, name);
        }
        return executionContext.addResult(this, documentType);
    }