Returns a copy of the pymongo collection with various options set up
9724
def _collection_with_options(self, kwargs):
        

        # class DocumentClassWithFields(self.document_class):
        #     _fetched_fields = kwargs.get("projection")
        #     mongokat_collection = self

        read_preference = kwargs.get("read_preference") or getattr(self.collection, "read_preference", None) or ReadPreference.PRIMARY

        if "read_preference" in kwargs:
            del kwargs["read_preference"]

        # Simplified tag usage
        if "read_use" in kwargs:
            if kwargs["read_use"] == "primary":
                read_preference = ReadPreference.PRIMARY
            elif kwargs["read_use"] == "secondary":
                read_preference = ReadPreference.SECONDARY
            elif kwargs["read_use"] == "nearest":
                read_preference = ReadPreference.NEAREST
            elif kwargs["read_use"]:
                read_preference = read_preferences.Secondary(tag_sets=[{"use": kwargs["read_use"]}])
            del kwargs["read_use"]

        write_concern = None
        if kwargs.get("w") is 0:
            write_concern = WriteConcern(w=0)
        elif kwargs.get("write_concern"):
            write_concern = kwargs.get("write_concern")

        codec_options = CodecOptions(
            document_class=(
                self.document_class,
                {
                    "fetched_fields": kwargs.get("projection"),
                    "mongokat_collection": self
                }
            )
        )

        return self.collection.with_options(
            codec_options=codec_options,
            read_preference=read_preference,
            write_concern=write_concern
        )
611011
def clone(self, **kwargs):
        

        grab = Grab(transport=self.transport_param)
        grab.config = self.dump_config()

        grab.doc = self.doc.copy()
        #grab.doc.grab = weakref.proxy(grab)

        for key in self.clonable_attributes:
            setattr(grab, key, getattr(self, key))
        grab.cookies = deepcopy(self.cookies)

        if kwargs:
            grab.setup(**kwargs)

        return grab
181837
public static <T> Collection<T> immutableCollectionCopy(Collection<T> collection) {
      if (collection == null) return null;
      if (collection.isEmpty()) return Collections.emptySet();
      if (collection.size() == 1) return Collections.singleton(collection.iterator().next());

      Collection<? extends T> copy = ObjectDuplicator.duplicateCollection(collection);
      if (copy == null)
         copy = attemptCopyConstructor(collection, Collection.class);
      if (copy == null)
         copy = new ArrayList<>(collection);

      return new ImmutableCollectionWrapper<>(copy);
   }
738203
function getCollection(key, collectionName, database, options, callback) {
    getDatabaseCached(database, options, getOrCreateCollection)

    function getOrCreateCollection(err, db) {
        if (err) {
            return callback(err)
        }

        // get the collection
        db.collection(collectionName, extend({
            safe: true
        }, options.collectionOptions), createIfNotExist)

        function createIfNotExist(err, collection) {
            // if not exist create it
            if (err && err.message.indexOf(" does not exist") !== -1) {
                return db.createCollection(collectionName, extend({
                    safe: true
                }, options.createCollectionOptions), returnCollection)
            }

            if (err) {
                return callback(err)
            }

            callback(null, collection)
        }
    }

    function returnCollection(err, col) {
        if (err) {
            return callback(err)
        }

        callback(null, col)
    }
}
199937
public static MongoCollection<Document> createCollection(MongoDatabase db,
            String collectionName, CreateCollectionOptions options) {
        db.createCollection(collectionName, options);
        return db.getCollection(collectionName);
    }
1244558
def copy(self):
        
        out = type(self)(
            name=self.__name,
            field=self.__field,
            display=self.__display,
            flags=self.__flags,
            default=self.__default,
            defaultOrder=self.__defaultOrder,
            getter=self.__gettermethod,
            setter=self.__settermethod,
            queryFilter=self.__query_filter,
            shortcut=self.__shortcut,
            readPermit=self.__readPermit,
            writePermit=self.__writePermit,
            order=self.__order
        )

        return out
910313
function(options) {
      options = options ? _.clone(options) : {};
      if (options.parse === void 0) options.parse = true;
      var collection = this;
      var success = options.success;
      options.success = function(resp, status, xhr) {
        var method = options.update ? 'update' : 'reset';
        collection[method](resp, options);
        if (success) success(collection, resp, options);
      };
      return this.sync('read', this, options);
    }
267307
def copy(self):
        
        options = {
            'op': self.__op,
            'caseSensitive': self.__caseSensitive,
            'value': copy.copy(self.__value),
            'inverted': self.__inverted,
            'functions': copy.copy(self.__functions),
            'math': copy.copy(self.__math)
        }
        return orb.Query(self.__model, self.__column, **options)
1332605
async def create_app_collections(db):
    ''' '''
    futures = []
    for model_class in MongoCollectionMixin.__subclasses__():
        if model_class._meta.concrete is True:
            futures.append(create_collection(db, model_class))

    await asyncio.gather(*futures)
11515
def collect(self):
        """"""

        if pymongo is None:
            self.log.error('Unable to import pymongo')
            return

        # we need this for backwards compatibility
        if 'host' in self.config:
            self.config['hosts'] = [self.config['host']]

        # convert network_timeout to integer
        if self.config['network_timeout']:
            self.config['network_timeout'] = int(
                self.config['network_timeout'])

        # use auth if given
        if 'user' in self.config:
            user = self.config['user']
        else:
            user = None

        if 'passwd' in self.config:
            passwd = self.config['passwd']
        else:
            passwd = None

        for host in self.config['hosts']:
            if len(self.config['hosts']) == 1:
                # one host only, no need to have a prefix
                base_prefix = []
            else:
                matches = re.search('((.+)\@)?(.+)?', host)
                alias = matches.group(2)
                host = matches.group(3)

                if alias is None:
                    base_prefix = [re.sub('[:\.]', '_', host)]
                else:
                    base_prefix = [alias]

            try:
                if ReadPreference is None:
                    conn = pymongo.Connection(
                        host,
                        network_timeout=self.config['network_timeout'],
                        slave_okay=True
                    )
                else:
                    conn = pymongo.Connection(
                        host,
                        network_timeout=self.config['network_timeout'],
                        read_preference=ReadPreference.SECONDARY,
                    )
            except Exception as e:
                self.log.error('Couldnt connect to mongodb: %s', e)
                continue

            # try auth
            if user:
                try:
                    conn.admin.authenticate(user, passwd)
                except Exception as e:
                    self.log.error(
                        'User auth given, but could not autheticate' +
                        ' with host: %s, err: %s' % (host, e))
                    return{}

            serverStatus = conn.db.command('serverStatus')
            engineStatus = conn.db.command('engineStatus')
            data = dict(serverStatus.items() + engineStatus.items())

            self._publish_transformed(data, base_prefix)
            if str_to_bool(self.config['simple']):
                data = self._extract_simple_data(data)

            self._publish_dict_with_prefix(data, base_prefix)
            db_name_filter = re.compile(self.config['databases'])
            ignored_collections = re.compile(self.config['ignore_collections'])
            for db_name in conn.database_names():
                if not db_name_filter.search(db_name):
                    continue
                db_stats = conn[db_name].command('dbStats')
                db_prefix = base_prefix + ['databases', db_name]
                self._publish_dict_with_prefix(db_stats, db_prefix)
                for collection_name in conn[db_name].collection_names():
                    if ignored_collections.search(collection_name):
                        continue
                    collection_stats = conn[db_name].command('collstats',
                                                             collection_name)
                    if str_to_bool(self.config['translate_collections']):
                        collection_name = collection_name.replace('.', '_')
                    collection_prefix = db_prefix + [collection_name]
                    self._publish_dict_with_prefix(collection_stats,
                                                   collection_prefix)
1203635
def get_collection(cls):
        """"""

        # By default the collection returned will be the published collection,
        # however if the `draft` flag has been set against the global context
        # (e.g `g`) then the collection returned will contain draft documents.

        if g.get('draft'):
            return getattr(
                cls.get_db(),
                '{collection}_draft'.format(collection=cls._collection)
                )

        return getattr(cls.get_db(), cls._collection)
119192
def execute(self):
        
        if self.query_set_obj is None:
            return []

        if self.is_mongoengine:
            result = self.query_set_obj.aggregate(*self.get_query())
        else:
            result = self.query_set_obj.aggregate(self.get_query())

        if IS_PYMONGO_3:
            result = list(result)
        else:
            result = result.get('result')
        if result:
            return result
        return []
201676
function(mongo_host, db, collection) {

    var arrayMongo = function() {
    };

    arrayMongo.prototype = Array.prototype;

    extend(arrayMongo.prototype, {
        /**
         * Store the parameters
         */
        host: function() {
            return mongo_host;
        },
        db: function() {
            return db;
        },
        mongoCollection: function() {
            return collection;
        },
        load: function(finished) {
            console.log('HERE');
            var self = this;
            var cname = this.mongoCollection();
            mongoCache.getConnection(this.host(), this.db(), (function(err, db) {
                if(err) return;
                var collection = db.collection(cname);
                collection.find().toArray(function(err, docs) {
                    if(err || docs.length < 1) {
                        finished();
                        return;
                    }

                    // Copy all the documents in the array
                    docs.forEach(function(doc) {
                        self.push(doc);
                    });
                    finished();
                }.bind(this));
            }).bind(this));
        },
        save: function() {
            var self = this;
            var cname = this.mongoCollection();
            mongoCache.getConnection(this.host(), this.db(), (function(err, db) {
                if(err) return;
                var collection = db.collection(cname);
                self.forEach(function(element) {
                    if(element['_id']) {
                        collection.update({_id: element['_id']}, element, function(){
                        });
                    }
                    else {
                        collection.insert(element, function(){
                        });
                    }
                });
            }).bind(this));
        }
    });

    // Create instance and return it
    return new arrayMongo();
}
155872
def get_mongo_version(self):
        
        if self._mongo_version:
            return self._mongo_version

        mongo_version = self.read_current_mongo_version()

        if not mongo_version:
            mongo_version = self.get_configured_mongo_version()

        self._mongo_version = mongo_version

        return self._mongo_version
524263
def copy(self):
		
		out = self._from_iterable(None)
		out._dict = self._dict.copy()
		out._size = self._size
		return out
369915
def export(self, exclude=[]):
        
        fields = ( (key, self.get_field(key)) for key in self.schema
            if not key.startswith("_") and key not in exclude )
        
        doc = {name: field.export() for name, field in fields}
        return doc
680653
def switch_db(name):
    
    with app.app_context():
        app.extensions['pymongo'][mongo.config_prefix] = mongo.cx, mongo.cx[name]