Skip to content

mongodb

ghdrako edited this page Feb 25, 2024 · 27 revisions

Instalacja

mdir \data\db
mongod.exe --dbpath d:\test\mongodb\data

Connect client

mongosh

Kolekcje

Insert

Dodanie do kolekcji me dokument address : {street : "Marszałkowska", city : "Warszawa"}:

db.me.insertOne(
{
	name : "Rafał",
	age : 35,
	address : {street : "Chłodna", city : "Warszawa"}
})

Delete

db.users.deleteOne({_id : 1})
db.users.deleteMany({name : "Ann"})
db.Users.deleteMany({})
db.Users.drop()

Count

db.Users.countDocuments()

Find

  • pobieranie "wszystkie" dokumenty - stremming danych - założony zostanie kursor i domyślnie dostaniemy 20 dokumentów iterująca sterownik będzie wysylal getMore(). Kazdy sterownik zapewnia mechanizm streemingu danych. Kursor nie jest izolowany - jesli dojda dokumenty to pojawiasie w kursorze. Klient mongodb opiera sie na sterowniku node.js. Find domyslnie streemuje dane za pomoca kursora. Jesli nieaktywnosc to kursor jest zamykany domyslnie po 10 minutach
db.me.find({})   # SELECT * FROM me;

Where

{ <field1>: <value1>, ... }

db.me.find({"age" : 30})  # select * from me where age = 30;

projekcja

db.<colection>.find(<where>,<projection>)
db.me.find({},{name : 1})  # domyślnie dorzuca tez id  select _id,name from me
db.me.find({},{name : 1, _id : 0}) # wymuszamy by nie zwrócił id select name from me
db.me.find({}, {name : 0})    # wszystkie pola oprocz name
db.me.find({"name" : "Artur"}).sort("age")  # sortowanie select * from me order by age;
db.me.find({"name" : "Artur"}).skip(10) 
db.me.find({"name" : "Artur"}).limit(10) # select * from me limit 10

Filtrowania - selektory zapytań $ne $gt $gte $lt $in $nin


Regex

Warunki logiczne $and $or $exist

db.me.find({"filed" : {$exist : 1}})
db.me.find({"filed" : {$exist : 0}})

findOne - zwraca pojedynczy losowy dokument spełniający filtr nie tworząc kursora

elemMatch

db.products.find({},($elemMatch : {"warehouses : {qty : {$lt : 10}}}})

$unset

Zmiana nazwy pola

db.me.updateMany({},{$unset : { "name" : "imie"}}) # zmiana nazwy - obsługa polskich znaków
db.me.updateMany({},{$unset : { "age" : ""}}) # usuniecie pola

Agregacje - Agregation Pipeline

  • wzorowana na operatorze | w linux - pipeline
  • definiujemy pipeline przez który przejdą nasze dane (kolekcja)
kolekcja ---> filtr ---> projekcja ---> grupowania ---> filtrowania ---> out ---> kolekcja 2

Każdy z etapów może występować dowolna ilość razy - tutaj np. 2 razy filtrowanie

db.

.agregate i dalej korki

Test

Clone this wiki locally