Zum Hauptinhalt springen

CRUD Operationen

Create

bei MySQL: Insert

Einzelnes Dokument einfügen

db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)

writeConcern

  • optional

Beispiel:

db.inventory.insertOne(
{
item: "canvas",
qty: 100,
tags: ["cotton"],
size: { h: 28, w: 35.5, uom: "cm" },
status: "A"
}
)

Rückgabe:

{
acknowledged: true,
insertedId
:
ObjectId("632f1fd57042d849480e4747")
}

Mehrere Dokumente einfügen

db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)

Beispiel:

db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A", tags: ["blank", "red"] },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A", tags: ["red", "blank"] },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D", tags: ["red", "blank", "plain"] },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D", tags: ["blank", "red"] },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A", tags: ["blue"] }
])

Rückgabe:

{
acknowledged: true,
insertedIds:
{
'0': ObjectId("632f4cad7042d849480e4750"),
'1': ObjectId("632f4cad7042d849480e4751"),
'2': ObjectId("632f4cad7042d849480e4752"),
'3': ObjectId("632f4cad7042d849480e4753"),
'4': ObjectId("632f4cad7042d849480e4754")
}

Read

db.collection.find( <query>, <projection>, <options> )

Alle finden

Beispiel:

db.inventory.find()

Rückgabe:

[
{
_id: ObjectId("632f57a67042d849480e4755"),
item: 'journal',
qty: 25,
size: {h: 14, w: 21, uom: 'cm'},
status: 'A',
tags: ['blank', 'red']
},
{
_id: ObjectId("632f57a67042d849480e4756"),
item: 'notebook',
qty: 50,
size: {h: 8.5, w: 11, uom: 'in'},
status: 'A',
tags: ['red', 'blank']
},
...

Filtern - query

Beispiel:

db.inventory.find( { status: "D" } )
db.inventory.find( { status: "D", item: "paper" } )

Rückgabe:

[
{
_id: ObjectId("632f57a67042d849480e4757"),
item: 'paper',
qty: 100,
size: {h: 8.5, w: 11, uom: 'in'},
status: 'D',
tags: ['red', 'blank', 'plain']
},
...

SQL:

SELECT *
FROM inventory
WHERE status = "D"

Operatoren

[
{
_id: ObjectId("632f57a67042d849480e4757"),
item: {$ne: 'paper'},
qty: {$lte: 100},
size: {h: {$gt: 8.5}, w: 11, uom: 'in'},
status: {$in: ['A', 'B' 'C']},
tags: {$nin: ['red', 'blank', 'plain']},
user_id: {$exists: true}
},
...
OperatorBedeutungZeichen
$eqequals=
$nenot equals!=
$gtgreater than>
$gtegreater than>=
$ltless than<
$lteless than equals<=
$inin, contains/includes
$ninnot in, doesn't contain/include
$existsexists
$elemMatchif an element of an array matches
AND-Bedingung

Mehrere Bedingungen werden durch ein Komma getrennt:

db.inventory.find( { status: "D", item: "paper" } )

SQL:

SELECT *
FROM inventory
WHERE status = "D"
AND item = "paper"
OR-Bedingung
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

SQL:

SELECT *
FROM inventory
WHERE status = "A"
OR qty < 30
Kombination von AND- und OR-Bedingung
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )

db.sales.find({
$or: [{ "items.name": "pens" }, { "items.tags": "writing" }],
})

SQL:

SELECT *
FROM inventory
WHERE status = "A"
AND (qty < 30 OR item LIKE "p%")

Hinweis: Möchte man einen Operator mehr als einmal verwenden, muss man explizit den $and-Operator verwenden. Denn in jedem JSON-Dokument darf jeder Key nur einmal vorkommen.

Beispiel: Folgendes funktioniert nicht, da es den Key $or mehr als einmal gibt:

db.routes.find({
$or: [{ dst_airport: "SEA" }, { src_airport: "SEA" }],
$or: [{ "airline": "American Airlines" }, { "airplane": 320 }]
})

Dies würde funktionieren:

db.routes.find({
$and: [
{ $or: [{ dst_airport: "SEA" }, { src_airport: "SEA" }] },
{ $or: [{ "airline": "American Airlines" }, { "airplane": 320 }] }
]
})

REGEX

Einen regulären Ausdruck (Regex, regular expression) kann man mit Schrägstrichen / anstatt der Gänsefüsschen " bei normalen Strings wahrnehmen.

Beispiel:

db.users.find({"name": /m/})

SQL:

SELECT *
FROM users
WHERE name LIKE '%m%'

Verschachtelung

db.inventory.find( { "pet.name": "Wuff" } )

Like

db.inventory.find( {
item: /^p/
} )

SQL:

SELECT *
FROM inventory
WHERE item LIKE "p%"

Array-Elemente filtern

Beispiel:

Dies findet alle Elemente, bei welchem das Array tags das Element blue beinhaltet. Es werden jedoch auch Objekte gefunden, bei welchen tags gleich dem String blue ist.

db.inventory.find( { tags: "blue" } )

Möchte man nur Objekte finden, bei welchen tags ein Array mit dem Element blue ist, kann man $elemMatch verwenden:

db.inventory.find( {
tags: {
$elemMatch: {
$eq: "blue"
}
}
} )

Dokumente zählen

Die Anzahl der Resultate eines find()-Befehls kann mit count() angezeigt werden:

db.people.find(<query>).count()

Folgende Befehle sind gleichwertig:

db.collection.countDocuments( <query>, <options> )
db.collection.count( <query>, <options> )

countDocuments() wird von der MongoDB-Dokumentation empfohlen. cursor.count() (bei find()) und db.collection.count() sind dabei als veraltet/deprecated markiert.

MongoDB Documentation - db.collection.countDocuments() StackOverflow - MongoDB count() versus countDocuments()

Eindeutige Dokumente filtern

Mit distinct() können alle Dokumente herausgefiltert werden, welche bei einem Feld (unter field) identisch sind.

db.collection.distinct(field, query, options)

SQL:

SELECT DISTINCT <field> FROM <table>;

Rückgabe ändern - projection

db.collection.find( { }, { <field1>: <value>, <field2>: <value> ... } )
ProjectionBeschreibung
<field>: <1 or true>zeigt Feld an
<field>: <0 or false>zeigt Feld nicht an

Das Feld _id wird standardmässig immer angezeigt. Ist es nicht erwünscht, muss es mit _id: 0 explizit ausgeblendet werden.

Beispiele:

db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

SQL:

SELECT _id, item, status
FROM inventory
WHERE status = 'A'

Verschachtelung:

db.inventory.find( { status: "A" }, { item: 1, "item.name": 1 } )

Rückgabe limitieren

db.people.find().limit(1)

Sortieren

db.collection.find().sort( { field: value } )

Werte für value:

ValueBedeutung
-1Descending, absteigende Sortierung
1Ascending, aufsteigende Sortierung

Beispiele:

db.inventory.find().sort({"qty": 1})
db.inventory.find().sort({"status":1, "item":1})

Update

Operatoren:

OperatorInhalt
$setDaten, welche geändert werden sollen
$currentDateweist gewähltem Attribut aktuelles Datum zu
$incWert addieren
$minändert das Feld nur, wenn der neue Wert kleiner als der existierende Wert ist
$maxändert das Feld nur, wenn der neue Wert grösser als der existierende Wert ist
$mulWert multiplizieren
$renameFeld umbenennen
$unsetlöscht ein Feld

Weitere Update-Operatoren findet man unter MongoDB Docs - Update Operators.

updateOne()

  • ändert den ersten gefundenen Datensatz
db.collection.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>,
let: <document>,
sort: <document>
}
)

Beispiel:

db.inventory.updateOne(
{ item: "stone" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)

updateMany()

  • ändert alle gefundenen Dokumente
db.collection.updateMany(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>,
let: <document>
}
)

Beispiel:

db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)

Werte aufgrund anderer Felder setzen

Mit $existingField kann der Wert eines anderen Feldes genommen werden.

db.people.updateMany(
{},
[{ $set: { newField: "$existingField" } }]
)

Beispiele

Erhöhen / Increase:

db.people.updateMany(
{},
{ $inc: { age: 3 } }
)

Erniedrigen / Decrease:

db.people.updateMany(
{},
{ $inc: { age: -3 } }
)

replaceOne()

  • ersetzt erstes gefundenes Dokument
db.collection.replaceOne(
<filter>,
<replacement>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
hint: <document|string>
}
)

Beispiel:

db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D", tags: ["red", "blank", "plain"] }
)

Delete

deleteOne()

  • löscht erstes gefundenes Dokument
db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document|string>
}
)

deleteMany()

  • löscht alle gefundenen Dokumente
db.collection.deleteMany(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)

Dies löscht alle Dokumente:

db.collection.deleteMany({})