CRUD
- Create
- Read
- Update
- Delete
Коллекция
@Serializable
data class Scholar(
val name: String,
val group: String
)
val scholars =
mongoDatabase
.getCollection<Scholar>()
.apply { drop() }
Create
scholars.insertOne(Scholar("Penny", "Girls"))
scholars.insertOne("{'name': 'Amy', 'group': 'Girls' }")
Sending command '{
"insert": "scholar", "ordered": true, "$db": "test",
"lsid": {"id": {"$binary": {
"base64": "UonhTNRHQJy7Y1Sn1TodHQ==", "subType": "04"}}},
"documents": [{"name": "Penny", "group": "Girls",
"_id": {"$oid": "642b8e7a5f80a934d58628c3"}}]}'
with request id 7 to database
test on connection [connectionId{localValue:3, serverValue:4}]
to server 127.0.0.1:27017
Create
scholars.insertMany(
arrayOf("Sheldon", "Leonard", "Howard", "Raj")
.map { Scholar(it, "Boys") }
)
{"insert": "scholar", "ordered": true, "$db": "test",
"lsid": {...},
"documents": [
{"name": "Sheldon", "group": "Boys", "_id": {...}},
{"name": "Leonard", "group": "Boys", "_id": {...}},
{"name": "Howard", "group": "Boys", "_id": {...}},
{"name": "Raj", "group": "Boys", "_id": {...}}]}
Read
println(scholars.find().toList())
println(scholars.findOne("{name: 'Penny'}"))
{"find": "scholar", "filter": {"name": "Penny"}, "limit": 1,
"singleBatch": true, "$db": "test", "lsid": {...}}
Received batch of 1 documents with cursorId 0
from server 127.0.0.1:27017 Scholar(name=Penny, group=Girls)
Read
val foundStudents: FindIterable<Scholar> =
scholars.find(Scholar::group eq "Boys")
.sort("{'name': 1}")
prettyPrintCursor(foundStudents)
{"find": "scholar", "filter": {"group": "Boys"},
"sort": {"name": 1}, "$db": "test", "lsid": {...}}
{"result": [
{ "name": "Howard",
"group": "Boys" },
{ "name": "Leonard",
"group": "Boys" },
{ "name": "Raj",
"group": "Boys" },
{ "name": "Sheldon",
"group": "Boys" }
]}
Filter
val bson1: Bson = Scholar::group eq "Boys"
infix fun <@OnlyInputTypes T>
KProperty<T?>.eq(value: T?): Bson =
Filters.eq(path(), value)
- Creates a filter that matches all documents where the value of the property equals the specified value. Note that this doesn’t actually generate a $eq operator, as the query language doesn’t require it.
Update
scholars.updateOne(
(Scholar::name eq "Amy"),
setValue(Scholar::name, "Amy Farrah Fowler")
)
{"update": "scholar", "ordered": true, "$db": "test",
"lsid": {...},
"updates": [{
"q": {"name": "Amy"},
"u": {"$set": {"name": "Amy Farrah Fowler"}}}]}
Update
scholars.updateMany(
"{'group' : 'Boys'}", "{'\$set' : {'group' : 'Man'}}")
{"update": "scholar", "ordered": true, "$db": "test",
"lsid": {...},
"updates": [{
"q": {"group": "Boys"},
"u": {"$set": {"group": "Man"}},
"multi": true}]}
Delete
scholars.deleteOne(Scholar::name eq "Penny")
{"delete": "scholar", "ordered": true, "$db": "test",
"lsid": {...},
"deletes": [
{"q": {"name": "Penny"},
"limit": 1}]}
Delete
scholars.deleteMany(Scholar::group eq "Man")
{"delete": "scholar", "ordered": true, "$db": "test",
"lsid": {...},
"deletes": [{
"q": {"group": "Man"},
"limit": 0}]}