import pymongo from bson.code import Code class MongoDBConnector: def __init__(self, dbname, host='localhost', port=27017): self.host = host self.port = port self.dbname = dbname def openConnection(self): self.client = pymongo.MongoClient(host=self.host, port=self.port) self.db = self.client[self.dbname] def closeConection(self): self.client.close() def getRecords(self, collection, filter=None, projection=None): if projection is None and not filter is None: return self.db[collection].find(filter=filter) elif not projection is None and filter is None: return self.db[collection].find(projection=projection) elif projection is None and filter is None: return self.db[collection].find() return self.db[collection].find(filter=filter, projection=projection) def getRecord(self, collection, filter=None, projection=None): if projection is None and not filter is None: return self.db[collection].find_one(filter=filter) elif not projection is None and filter is None: return self.db[collection].find_one(projection=projection) elif projection is None and filter is None: return self.db[collection].find_one() return self.db[collection].find_one(filter=filter, projection=projection) def execAggreation(self, collection, pipeline): return self.db[collection].aggregate(pipeline=pipeline) def execMapReduce(self, collection, mapper, reducer, out, query=None): self.db[out].drop() if query is None: return self.db[collection].map_reduce(mapper, reducer, out) return self.db[collection].map_reduce(mapper, reducer, out, query=query) if __name__ == '__main__': dbname = "BD" db = MongoDBConnector(dbname=dbname) collection = "documents" filter = { "$text": { "$search": "coffee", "$language": "english", "$caseSensitive": False, "$diacriticSensitive": False } } projection = { "lemmaText": 1 } db.openConnection() print("Test 1") doc = db.getRecord(collection, filter, projection) print(doc) print("Test 2") doc = db.getRecord(collection, filter=filter) print(doc) print("Test 3") doc = db.getRecord(collection, projection=projection) print(doc) print("Test 4") doc = db.getRecord(collection) print(doc) db.closeConection() # Exeplu folosire index geospatial. filter = { "geoLocation": { "$near": [25, 25] } } projection = {"geoLocation": 1, "lemmaText": 1 } db.openConnection() docs = db.getRecords(collection, filter, projection) for doc in docs: print(doc) db.closeConection() # Exemplu Aggregation Pipeline q = {"gender": "male"} pipeline = [ { "$match": q }, { "$project": { "words": { "$split": ["$lemmaText", " "]}}}, { "$unwind": "$words" }, { "$group": { "_id": "$words", "counts": { "$sum": 1 } } } ] db.openConnection() docs = db.execAggreation(collection, pipeline) for doc in docs: print(doc) db.closeConection() # Exemplu MapReduce mapper = Code(""" function() { var tokens = this.lemmaText.split(" "); for (var idx=0; idx